autofac v4.0+通過配置文件的方式注冊組件


 最近在看李玉寶 / OpenAuth.Net的項目代碼,新手表示看不懂.所以,不管三七二十一,模仿是最好的學習,於是我決定自己創建一個項目,把人家的代碼一點一點拷貝過來,細細品味.

在研究的過程中,我發現大神用autofac是通過配置文件的方式.Autofac.Configuration的版本是V3.3,然后我創建的項目用的是V4.0.1. 本來是想用代碼注冊組件的,但是以看到大神是通過配置文件注冊的,於是乎,不管三七二十一,我就定下了一個小目標,我要用v4.0.1版本來完成使用配置文件的方式來注冊組件.

廢話不多說官網的文檔在http://autofac.readthedocs.io/en/latest/configuration/xml.html#configuring-with-microsoft-configuration-4-0  

里面有一段Demo,如下圖

但是當你把代碼拷貝到項目時會發現AddJsonFile方法是報錯的,如下圖

解決思路:我要怎么樣才能完成config.AddJsonFile這個方法呢.

在度娘后發現基本所有的網頁都是用AddJsonFile這個方法

原因是Microsoft.Extensions.Configuration這個dll有3個版本

 

最后實在是無奈的我,下載了Microsoft.Extensions.Configuration組件的源碼, 下載地址:https://codeload.github.com/aspnet/Configuration/zip/dev

在研究后發現IConfigurationSource的實現類(全是抽象類)有

MemoryConfigurationSource
CommandLineConfigurationSource
EnvironmentVariablesConfigurationSource
FileConfigurationSource 
AzureKeyVaultConfigurationSource

根據上面的AddJsonFile方法,我猜我需要的FileConfigurationSource,然后我又去找該方法類的實現類,發現了大致

IniConfigurationSource
JsonConfigurationSource
XmlConfigurationSource

同理,根據AddJsonFile方法,我猜測,我需要的是JsonConfigurationSource類.

有了上述的猜測,我就可以開始動手了.

 在vs的項目的引用中右鍵,找到nuget,搜索JsonConfigurationProvider,然后安裝

接着,又是AddJsonFile這句話,我選擇了用json的方式,而不是xml來配置,配置文件內容最后附上.

最后,附上主要代碼(我是asp.net mvc項目)

//1. Create a ContainerBuilder.
var builder = new ContainerBuilder();
IConfigurationBuilder config = new ConfigurationBuilder();

IConfigurationSource autofacJsonConfigSource = new JsonConfigurationSource()
{
Path = "/config/autofac.json",
Optional = false,//boolean,默認就是false,可不寫
ReloadOnChange = false,//同上
};

config.Add(autofacJsonConfigSource);

// Register the ConfigurationModule with Autofac.
var module = new ConfigurationModule(config.Build());
builder.RegisterModule(module);

// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);


//3.Build the container and store it for later use.
var container = builder.Build();

//4.實現DI(DependencyResolver方式)
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

 最后,關於配置文件的參數說明,鏈接:https://github.com/autofac/Documentation/blob/master/docs/configuration/xml.rst

 附:我的autofac.json文件內容 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM