码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-09-15 22:52:06      阅读:1188      评论:0      收藏: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+通过配置文件的方式注册组件

标签:

原文地址:http://www.cnblogs.com/geliang/p/5875522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!