簡(jiǎn)介
Autofac是一款I(lǐng)OC框架,比較于其他的IOC框架凯亮,如Spring.NET莫湘,Unity贝搁,Castle等等所包含的必逆,它很輕量級(jí)性能上非常高怠堪。
官方網(wǎng)站http://autofac.org/
源碼下載地址https://github.com/autofac/Autofac
最新版本下載可以看到,包括源碼名眉,示例文檔粟矿,與之相關(guān)的測(cè)試項(xiàng)目,生成的DLL文件损拢,其他文檔
控制反轉(zhuǎn)和依賴注入
關(guān)于控制反轉(zhuǎn)和依賴注入的文章和書(shū)籍很多陌粹,對(duì)其定義也解釋的也仁者見(jiàn)仁,這里就不贅述了福压,這是本人(只代表個(gè)人觀點(diǎn))的理解:
- 控制反轉(zhuǎn)(IoC/Inverse Of Control): 調(diào)用者不再創(chuàng)建被調(diào)用者的實(shí)例掏秩,由autofac框架實(shí)現(xiàn)(容器創(chuàng)建)所以稱為控制反轉(zhuǎn)或舞。
- 依賴注入(DI/Dependence injection) : 容器創(chuàng)建好實(shí)例后再注入調(diào)用者稱為依賴注入。
基本使用
安裝Autofac
Install-Package Autofac
官方使用簡(jiǎn)單介紹
Adding Components
var builder = new ContainerBuilder();
Autofac can use a Linq expression, a .NET type, or a pre-built instance as a component:
builder.Register(c => new TaskController(c.Resolve<ITaskRepository>()));
builder.RegisterType<TaskController>();
builder.RegisterInstance(new TaskController());
Or, Autofac can find and register the component types in an assembly:
builder.RegisterAssemblyTypes(controllerAssembly);
Calling Build() creates a container:
var container = builder.Build();
To retrieve a component instance from a container, a service is requested. By default, components provide their concrete type as a service:
var taskController = container.Resolve<TaskController>();
To specify that the component’s service is an interface, the As()
method is used at registration time:
builder.RegisterType<TaskController>().As<IController>();
// enabling
var taskController = container.Resolve<IController>();
方法一:
var builder = new ContainerBuilder();
builder.RegisterType<TestService>();
builder.RegisterType<TestDao>().As<ITestDao>();
return builder.Build();
方法二:
為了統(tǒng)一管理 IoC 相關(guān)的代碼蒙幻,并避免在底層類庫(kù)中到處引用 Autofac 這個(gè)第三方組件映凳,定義了一個(gè)專門(mén)用于管理需要依賴注入的接口與實(shí)現(xiàn)類的空接口 IDependency:
/// <summary>
/// 依賴注入接口,表示該接口的實(shí)現(xiàn)類將自動(dòng)注冊(cè)到IoC容器中
/// </summary>
public interface IDependency
{ }
這個(gè)接口沒(méi)有任何方法邮破,不會(huì)對(duì)系統(tǒng)的業(yè)務(wù)邏輯造成污染诈豌,所有需要進(jìn)行依賴注入的接口,都要繼承這個(gè)空接口抒和,例如:
業(yè)務(wù)單元操作接口:
/// <summary>
/// 業(yè)務(wù)單元操作接口
/// </summary>
public interface IUnitOfWork : IDependency
{
...
}
Autofac 是支持批量子類注冊(cè)的矫渔,有了 IDependency 這個(gè)基接口,我們只需要 Global 中很簡(jiǎn)單的幾行代碼摧莽,就可以完成整個(gè)系統(tǒng)的依賴注入匹配:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
Type baseType = typeof(IDependency);
// 獲取所有相關(guān)類庫(kù)的程序集
Assembly[] assemblies =...
builder.RegisterAssemblyTypes(assemblies)
.Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
.AsImplementedInterfaces().InstancePerLifetimeScope();
//InstancePerLifetimeScope 保證對(duì)象生命周期基于請(qǐng)求IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
如此庙洼,只有站點(diǎn)主類庫(kù)需要引用 Autofac,而不是到處都存在著注入的相關(guān)代碼镊辕,大大降低了系統(tǒng)的復(fù)雜度送膳。
參考:http://www.cnblogs.com/guomingfeng/p/osharp-layer.html
創(chuàng)建實(shí)例方法
1、InstancePerDependency
對(duì)每一個(gè)依賴或每一次調(diào)用創(chuàng)建一個(gè)新的唯一的實(shí)例丑蛤。這也是默認(rèn)的創(chuàng)建實(shí)例的方式叠聋。
官方文檔解釋:
Configure the component so that every dependent component or call to Resolve() gets a new, unique instance (default.)
2、InstancePerLifetimeScope
在一個(gè)生命周期域中受裹,每一個(gè)依賴或調(diào)用創(chuàng)建一個(gè)單一的共享的實(shí)例碌补,且每一個(gè)不同的生命周期域,實(shí)例是唯一的棉饶,不共享的厦章。
官方文檔解釋:
Configure the component so that every dependent component or call to Resolve() within a single ILifetimeScope gets the same, shared instance. Dependent components in different lifetime scopes will get different instances.
3、InstancePerMatchingLifetimeScope
在一個(gè)做標(biāo)識(shí)的生命周期域中照藻,每一個(gè)依賴或調(diào)用創(chuàng)建一個(gè)單一的共享的實(shí)例袜啃。打了標(biāo)識(shí)了的生命周期域中的子標(biāo)識(shí)域中可以共享父級(jí)域中的實(shí)例。若在整個(gè)繼承層次中沒(méi)有找到打標(biāo)識(shí)的生命周期域幸缕,則會(huì)拋出異常:DependencyResolutionException群发。
官方文檔解釋:
Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope tagged with any of the provided tags value gets the same, shared instance. Dependent components in lifetime scopes that are children of the tagged scope will share the parent's instance. If no appropriately tagged scope can be found in the hierarchy an DependencyResolutionException is thrown.
4、InstancePerOwned
在一個(gè)生命周期域中所擁有的實(shí)例創(chuàng)建的生命周期中发乔,每一個(gè)依賴組件或調(diào)用Resolve()方法創(chuàng)建一個(gè)單一的共享的實(shí)例熟妓,并且子生命周期域共享父生命周期域中的實(shí)例。若在繼承層級(jí)中沒(méi)有發(fā)現(xiàn)合適的擁有子實(shí)例的生命周期域栏尚,則拋出異常:DependencyResolutionException起愈。
官方文檔解釋:
Configure the component so that every dependent component or call to Resolve() within a ILifetimeScope created by an owned instance gets the same, shared instance. Dependent components in lifetime scopes that are children of the owned instance scope will share the parent's instance. If no appropriate owned instance scope can be found in the hierarchy an DependencyResolutionException is thrown.
5、SingleInstance
每一次依賴組件或調(diào)用Resolve()方法都會(huì)得到一個(gè)相同的共享的實(shí)例。其實(shí)就是單例模式抬虽。
官方文檔解釋:
Configure the component so that every dependent component or call to Resolve() gets the same, shared instance.
6官觅、InstancePerHttpRequest
在一次Http請(qǐng)求上下文中,共享一個(gè)組件實(shí)例。僅適用于asp.net mvc開(kāi)發(fā)阐污。
參考鏈接:
autofac 創(chuàng)建實(shí)例方法總結(jié):
http://www.cnblogs.com/manglu/p/4115128.html
AutoFac使用方法總結(jié):Part I:
http://niuyi.github.io/blog/2012/04/06/autofac-by-unit-test/