Autofac 依賴注入框架 使用

簡(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/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末缰猴,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子疤剑,更是在濱河造成了極大的恐慌滑绒,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件隘膘,死亡現(xiàn)場(chǎng)離奇詭異疑故,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)弯菊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)纵势,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人管钳,你說(shuō)我怎么就攤上這事钦铁。” “怎么了才漆?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵牛曹,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我醇滥,道長(zhǎng)黎比,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任鸳玩,我火速辦了婚禮阅虫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘不跟。我一直安慰自己颓帝,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布窝革。 她就那樣靜靜地躺著购城,像睡著了一般。 火紅的嫁衣襯著肌膚如雪聊闯。 梳的紋絲不亂的頭發(fā)上工猜,一...
    開(kāi)封第一講書(shū)人閱讀 51,688評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音菱蔬,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛拴泌,可吹牛的內(nèi)容都是我干的魏身。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼蚪腐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼箭昵!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起回季,我...
    開(kāi)封第一講書(shū)人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤家制,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后泡一,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體颤殴,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年鼻忠,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了涵但。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡帖蔓,死狀恐怖矮瘟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情塑娇,我是刑警寧澤澈侠,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站埋酬,受9級(jí)特大地震影響埋涧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜奇瘦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一棘催、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧耳标,春花似錦醇坝、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至砸琅,卻和暖如春宋距,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背症脂。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工谚赎, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淫僻,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓壶唤,卻偏偏與公主長(zhǎng)得像雳灵,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子闸盔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容