autofac v4.0+通过配置文件的方式注册组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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文件内容 

 

技术分享

 

以上是关于autofac v4.0+通过配置文件的方式注册组件的主要内容,如果未能解决你的问题,请参考以下文章

IoC容器Autofac正篇之类型注册

Autofac官方文档翻译--注册组件--4组件扫描

Autofac依赖注入

Autofac依赖注入

Autofac和nopcommerce中的Autofac, 还有反射

一文学会Autofac的基础操作:几种实现注册方式3种注入方式生命周期AOP以及过滤器实现依赖注入...