autofac是比較簡單易用的IOC容器。下面我們展示如何通過json配置文件,來進(jìn)行控制反轉(zhuǎn)。
需要用到以下程序集??梢酝ㄟ^nugget分別安裝
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.Json
?Autofac.Configuration.dll
注意,項(xiàng)目目標(biāo)框架最好設(shè)置為.NET Framework 4.6.1及以上。因?yàn)镸icrosoft.Extensions.Configuration.dll,依賴.NETStandard2.0?
?下表列出了 .NET Standard 的所有版本及其支持的平臺(tái)

AutofacExt幫助類
using Autofac;using Autofac.Configuration;using Microsoft.Extensions.Configuration;namespace autofacConsole
{
? ? publicstaticclass AutofacExt
? ? {
? ? ? ? privatestatic IContainer _container;
? ? ? ? publicstaticvoid InitAutofac()
? ? ? ? {
? ? ? ? ? ? // Add the configuration to the ConfigurationBuilder.varconfig =new ConfigurationBuilder();
? ? ? ? ? ? config.AddJsonFile("autofac.json");
? ? ? ? ? ? // Register the ConfigurationModule with Autofac.varmodule =new ConfigurationModule(config.Build());
? ? ? ? ? ? varbuilder =new ContainerBuilder();
? ? ? ? ? ? builder.RegisterModule(module);
? ? ? ? ? ? // Set the dependency resolver to be Autofac._container = builder.Build();
? ? ? ? }
? ? ? ? ///<summary>/// 從容器中獲取對(duì)象
? ? ? ? ///</summary>///<typeparam name="T"></typeparam>publicstaticT GetFromFac()
? ? ? ? {
? ? ? ? ? ? return_container.Resolve();
? ? ? ? ? ? //? return (T)DependencyResolver.Current.GetService(typeof(T));? ? ? ? }
? ? ? ? publicstaticT GetFromFac(string name)
? ? ? ? {
? ? ? ? ? ? return_container.ResolveNamed(name);
? ? ? ? }
? ? }
}
?客戶端調(diào)用
publicinterface IOutput
? ? {
? ? ? ? voidWrite(stringcontent);? ? }
publicclass ConsoleOutput : IOutput
? ? {
? ? ? ? publicvoidWrite(string content)
? ? ? ? {
? ? ? ? ? ? Console.WriteLine(content);
? ? ? ? }
? ? }class Program
? ? {? ? ? ?
? ? ? ? staticvoidMain(string[] args)
? ? ? ? {
? ? ? ? ? AutofacExt.InitAutofac();
? ? ? ? ? ? varwriter =AutofacExt.GetFromFac();
? ? ? ? ? ? writer.WriteDate();
? ? ? ? ? ? Console.ReadKey();
? ? ? ? }
? ? }? ?
?json配置文件配置
Autofac.json?
{
? "defaultAssembly": "autofacConsole",
? "components": [
? ? {
? ? ? "type": "autofacConsole.ConsoleOutput, autofacConsole",
? ? ? "services": [
? ? ? ? {
? ? ? ? ? "type": "autofacConsole.IOutput,autofacConsole"? ? ? ? }
? ? ? ],
? ? ? "instanceScope": "single-instance",
? ? ? "injectProperties":true? ? }
? ]
}
設(shè)置為如果較新則復(fù)制
