當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
autofac JSON文件配置
生活随笔
收集整理的這篇文章主要介紹了
autofac JSON文件配置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
autofac是比較簡單易用的IOC容器。下面我們展示如何通過json配置文件,來進行控制反轉。
需要用到以下程序集。可以通過nugget分別安裝
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.Json
?Autofac.Configuration.dll
?
注意,項目目標框架最好設置為.NET Framework 4.6.1及以上。因為Microsoft.Extensions.Configuration.dll,依賴.NETStandard2.0?
?下表列出了 .NET Standard 的所有版本及其支持的平臺
?
AutofacExt幫助類
using Autofac; using Autofac.Configuration; using Microsoft.Extensions.Configuration;namespace autofacConsole {public static class AutofacExt{private static IContainer _container;public static void InitAutofac(){// Add the configuration to the ConfigurationBuilder.var config = new ConfigurationBuilder();config.AddJsonFile("autofac.json");// Register the ConfigurationModule with Autofac.var module = new ConfigurationModule(config.Build());var builder = new ContainerBuilder();builder.RegisterModule(module);// Set the dependency resolver to be Autofac._container = builder.Build();}/// <summary>/// 從容器中獲取對象/// </summary>/// <typeparam name="T"></typeparam>public static T GetFromFac<T>(){return _container.Resolve<T>();// return (T)DependencyResolver.Current.GetService(typeof(T)); }public static T GetFromFac<T>(string name){return _container.ResolveNamed<T>(name);}} }?客戶端調用
public interface IOutput{void Write(string content);}public class ConsoleOutput : IOutput{public void Write(string content){Console.WriteLine(content);}}class Program{ static void Main(string[] args){AutofacExt.InitAutofac();var writer =AutofacExt.GetFromFac<IOutput>();writer.WriteDate();Console.ReadKey();}}
?
?json配置文件配置
Autofac.json?
{"defaultAssembly": "autofacConsole","components": [{"type": "autofacConsole.ConsoleOutput, autofacConsole","services": [{"type": "autofacConsole.IOutput,autofacConsole"}],"instanceScope": "single-instance","injectProperties": true}] }設置為如果較新則復制
?
參考資料:
https://github.com/autofac/Autofac
https://autofac.readthedocs.io/en/latest/getting-started/index.html
https://autofac.readthedocs.io/en/latest/configuration/xml.html
?
轉載于:https://www.cnblogs.com/xinyf/p/9842205.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的autofac JSON文件配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows MySQL8.0安装出错
- 下一篇: MySQL递归查询父节点或递归查询子节点