Autofac通过配置的方式
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