日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

微軟企業(yè)庫4.1學(xué)習(xí)筆記(二十五)Unity依賴注入

系統(tǒng) 2309 0

  Unity模塊的亮點(diǎn)

  Unity模塊包括了下面的特點(diǎn)

  •   提供了一個(gè)創(chuàng)建對(duì)象,以及依賴的對(duì)象的方法
  •   提供的RegisterType方法用來在容器中注冊(cè)類型和映射,Resolve方法可以返回任何依賴對(duì)象的實(shí)例。
  •   提供控制反轉(zhuǎn)IOC功能,通過預(yù)先配置注入類的對(duì)象來實(shí)現(xiàn)。你可以在構(gòu)造函數(shù)中指明一個(gè)類或者接口(構(gòu)造函數(shù)注入),或者是使用attribute的屬性注入,和方法調(diào)用注入。
  •   支持容器繼承,容器可以有子容器,支持對(duì)象從子容器傳遞到父容器中。
  •   可以從標(biāo)準(zhǔn)的配置文件中讀取信息,例如xml文件
  •   對(duì)類的定義沒有任何要求。在類上不需要添加attribute(除非使用屬性注入或者是方法調(diào)用注入),在類聲明中沒有任何限制。
  •   支持自定義容器,例如,你可以在方法中實(shí)現(xiàn)額外的對(duì)象構(gòu)造,和容器功能,例如容器的緩存功能。

  什么時(shí)候使用Unity模塊

  依賴注入提供了簡(jiǎn)化代碼的機(jī)會(huì),抽象對(duì)象之間的依賴,自動(dòng)產(chǎn)生依賴對(duì)象的實(shí)例。但是,處理的過程對(duì)性能上有一點(diǎn)小的損失,而且可能會(huì)使得只需要簡(jiǎn)單依賴的地方變得復(fù)雜。

  通常來說,在下列情況你應(yīng)該使用Unity模塊:

  •   對(duì)象和類與其他對(duì)象和類有依賴關(guān)系。
  •   你的依賴關(guān)系是復(fù)雜的,或者是需要抽象。
  •   你需要構(gòu)造函數(shù)、方法、或者是屬性注入的功能。
  •   你需要管理對(duì)象實(shí)例的生命周期。
  •   你需要在運(yùn)行的時(shí)候可以配置和改變依賴關(guān)系。
  •   你需要在web應(yīng)用中緩存或者是持久化依賴關(guān)系。

  在下面的情況,你不應(yīng)該使用Unity模塊

  •   你的對(duì)象和類與其他的對(duì)象和類沒有依賴關(guān)系。
  •   你的依賴關(guān)系很簡(jiǎn)單,不需要抽象。

  在開發(fā)的過程中使用Unity模塊

  這個(gè)主題描述如何在應(yīng)用開發(fā)中使用Unity模塊。如何創(chuàng)建對(duì)象實(shí)例。

  使用Unity模塊的系統(tǒng)需要

  最小需要如下:

  •   Microsoft Windows XP Professional,Windows Server 2003,Windows Server 2008 or Windows Vista operating System。
  •   Microsoft .NET Framework 2.0,3.0 or 3.5。
  •   Microsoft Visual Studio 2005 or 2008 development system。

  配置Unity模塊

  Unity模塊可以從xml配置文件中讀取配置信息。默認(rèn)情況下,就是應(yīng)用中的app.config或者是web.config文件。你也可以從其他xml文件,或者是其他來源加載配置信息。

  在運(yùn)行的時(shí)候配置容器

  1.格式化Unity配置文件

  下面的xml格式就是Unity的配置格式。

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> < configuration > ?
  < configSections > ?
    < section? name ="unity" ?type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,?Microsoft.Practices.Unity.Configuration" ? />
  ? </ configSections > ?
  < unity > ?...?...?
  </ unity > ?...?...?
</ configuration >

?  下面是一個(gè)比較完整的配置文件

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> <? xml?version="1.0"?encoding="utf-8"? ?> ?
< configuration > ?
  < configSections > ?
    < section? name ="unity" ?type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft?patterns?&?practices?–?Unity?Application?Block?1.2?–?October?2008?27
Microsoft.Practices.Unity.Configuration,?=1.2.0.0,?Culture=neutral,?PublicKeyToken=31bf3856ad364e35"
? /> ?
  </ configSections >
  ? < unity > ?
    < typeAliases > ? <!-- ?Lifetime?manager?types? --> ?
      < typeAlias? alias ="singleton" ?type ="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,?Microsoft.Practices.Unity" ? /> ?
      < typeAlias? alias ="perThread" ?type ="Microsoft.Practices.Unity.PerThreadLifetimeManager,?Microsoft.Practices.Unity" ? />
      ? < typeAlias? alias ="external" ?type ="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,?Microsoft.Practices.Unity" ? /> ? <!-- ?User-defined?type?aliases? --> ?
      < typeAlias? alias ="IMyInterface" ?type ="MyApplication.MyTypes.MyInterface,?MyApplication.MyTypes" ? /> ?
      < typeAlias? alias ="MyRealObject" ?type ="MyApplication.MyTypes.MyRealObject,?MyApplication.MyTypes" ? /> ?
      < typeAlias? alias ="IMyService" ?type ="MyApplication.MyTypes.MyService,?MyApplication.MyTypes" ? /> ?
      < typeAlias? alias ="MyDataService" ?type ="MyApplication.MyTypes.MyDataService,?MyApplication.MyTypes" ? /> ?
      < typeAlias? alias ="MyCustomLifetime" ?type ="MyApplication.MyLifetimeManager,?MyApplication.MyTypes" ? /> ?
    </ typeAliases > ?
    < containers > ?
      < container? name ="containerOne" > ?
        < types > ? <!-- ?Type?mapping?with?no?lifetime?–?defaults?to?"transient"? --> ?
          < type? type ="Custom.MyBaseClass" ?mapTo ="Custom.MyConcreteClass" ? /> ? <!-- ?Type?mapping?using?aliases?defined?above? --> ?
          < type? type ="IMyInterface" ?mapTo ="MyRealObject" ?name ="MyMapping" ? /> ? <!-- ?Lifetime?managers?specified?using?the?type?aliases? --> ?
          < type? type ="Custom.MyBaseClass" ?mapTo ="Custom.MyConcreteClass" > ? < lifetime? type ="singleton" ? /> ? </ type >
28?Microsoft?patterns?&?practices?–?Unity?Application?Block?1.2?–?October?2008
< type? type ="IMyInterface" ?mapTo ="MyRealObject" ?name ="RealObject" > ? < lifetime? type ="perThread" ? /> ? </ type > ? < type? type ="IMyInterface" ?mapTo ="MyRealObject" ?name ="RealObject" > ? < lifetime? type ="external" ? /> ? </ type > ? <!-- ?Lifetime?manager?specified?using?the?full?type?name? --> ? <!-- ?Any?initialization?data?specified?for?the?lifetime?manager? --> ? <!-- ?will?be?converted?using?the?default?type?converter? --> ? < type? type ="Custom.MyBaseClass" ?mapTo ="Custom.MyConcreteClass" > ? < lifetime? value ="sessionKey" ?type ="MyApplication.MyTypes.MyLifetimeManager,?MyApplication.MyTypes" ? /> ? </ type > ? <!-- ?Lifetime?manager?initialization?using?a?custom?TypeConverter? --> ? < type? type ="IMyInterface" ?mapTo ="MyRealObject" ?name ="CustomSession" > ? < lifetime? type ="MyCustomLifetime" ?value ="ReverseKey" ?typeConverter ="MyApplication.MyTypes.MyTypeConverter,?MyApplication.MyTypes" ? /> ? </ type > ? <!-- ?Object?with?injection?parameters?defined?in?configuration? --> ? <!-- ?Type?mapping?using?aliases?defined?above? --> ? < type? type ="IMyService" ?mapTo ="MyDataService" ?name ="DataService" > ? < typeConfig? extensionType ="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,?Microsoft.Practices.Unity.Configuration" > ? < constructor > ? < param? name ="connectionString" ?parameterType ="string" > ? < value? value ="AdventureWorks" /> ? </ param > ? < param? name ="logger" ?parameterType ="ILogger" > ? < dependency? /> ? </ param > ? </ constructor > ? < property? name ="Logger" ?propertyType ="ILogger" ? /> ? < method? name ="Initialize" > ? < param? name ="connectionString" ?parameterType ="string" > ? < value? value ="contoso" /> ? </ param > ? < param? name ="dataService" ?parameterType ="IMyService" > ? < dependency? /> ? </ param > ? </ method > ? </ typeConfig > ? </ type >
Microsoft?patterns?&?practices?–?Unity?Application?Block?1.2?–?October?2008?29
</ types > ? < instances > ? < add? name ="MyInstance1" ?type ="System.String" ?value ="Some?value" ? /> ? < add? name ="MyInstance2" ?type ="System.DateTime" ?value ="2008-02-05T17:50:00" ? /> ? </ instances > ? < extensions > ? < add? type ="MyApp.MyExtensions.SpecialOne" ? /> ? </ extensions > ? < extensionConfig > ? < add? name ="MyExtensionConfigHandler" ?type ="MyApp.MyExtensions.SpecialOne.ConfigHandler" ? /> ? </ extensionConfig >
    ? </ container > ? <!-- ?...?more?containers?here?...? --> ? </ containers > ?
  </ unity > ?
</ configuration >

?

  將配置信息加載到容器中

  Unity不會(huì)自動(dòng)讀取配置信息來創(chuàng)建和準(zhǔn)備好一個(gè)容器。你需要在應(yīng)用中用代碼來初始化容器,你也可以用代碼注冊(cè)類型,類型映射,任何從文件中讀取的擴(kuò)展信息都可以用代碼來創(chuàng)建。

  如果配置定義了一個(gè)未命名的容器,這個(gè)沒有名字的容器就是默認(rèn)的容器。你也可以給容器命名。你可以將每一個(gè)容器的配置信息加載到容器中,

  下面的代碼就是初始化一個(gè)新的容器,然后加載配置文件中配置的類型,映射,和擴(kuò)展定義。

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> IUnityContainer?container? = ? new ?UnityContainer();?
UnityConfigurationSection?section? = ?(UnityConfigurationSection)ConfigurationManager.GetSection( " unity " );?
section.Containers.Default.Configure(container);

?

  加載容器的時(shí)候,你也可以使用容器的名稱進(jìn)行加載。下面的代碼就是加載了一個(gè)名為containerOne的容器。

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> IUnityContainer?container? = ? new ?UnityContainer();
?UnityConfigurationSection?section? = ?(UnityConfigurationSection)ConfigurationManager.GetSection( " unity " );?
section.Containers[ " containerOne " ].Configure(container);

?

  創(chuàng)建一個(gè)在配置文件中定義的有繼承關(guān)系嵌套的容器,你可以用CreateChildContainer方法加載每一個(gè)適當(dāng)?shù)娜萜餍畔ⅰ?

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> IUnityContainer?parentContainer? = ? new ?UnityContainer();?
IUnityContainer?childContainer? = ?parentContainer.CreateChildContainer();?
UnityConfigurationSection?section?
= ?(UnityConfigurationSection)ConfigurationManager.GetSection( " unity " );?
section.Containers[ " containerOne " ].GetConfigCommand().Configure(parentContainer);?
section.Containers[ " nestedChildContainer " ].Configure(childContainer);

?

?

  你不能在配置文件中嵌套容器,在containers節(jié)中的所有container元素都是同一個(gè)級(jí)別的元素。容器嵌套是通過代碼來創(chuàng)建,并且加載適當(dāng)?shù)娜萜鳌?

  使用可替代的配置源

  如果有需要的話,你可以使用任何xml文件或者是其他源作為配置信息。例如,你可以用System.Configuration.Configuration類獲取任何xml文件的配置信息,下面的代碼中就是這樣用的。

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> ExeConfigurationFileMap?map? = ? new ?ExeConfigurationFileMap();
?map.ExeConfigFilename? = ? " MyConfig.config " ;?
System.Configuration.Configuration?config? = ?ConfigurationManager.OpenMappedExeConfiguration(map,?ConfigurationUserLevel.None);
?UnityConfigurationSection?section? = ?(UnityConfigurationSection)config.GetSection( " unity " );
?IUnityContainer?container? = ? new ?UnityContainer();
?section.Containers[ " myContainer " ].Configure(container);

?

  配置支持?jǐn)?shù)組

  Unity支持設(shè)計(jì)時(shí)數(shù)組參數(shù),和運(yùn)行是數(shù)組參數(shù)。

  在設(shè)計(jì)的時(shí)候配置支持?jǐn)?shù)組參數(shù)

  在配置文件中使用array元素作為list的代表。array元素描述了一個(gè)包含注冊(cè)實(shí)例和類型映射的數(shù)組。array可以嵌套使用,包含下面三個(gè)子元素:

  •   array
  •   dependency
  •   value
    代碼
    <!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> < typeAlias? alias ="ILoggerArray" ?type ="Microsoft.Practices.Unity.TestSupport.ILogger[],?TestSupport.Unity" ? /> ?
  • < typeAlias? alias ="ArrayConstructor" ?type ="Microsoft.Practices.Unity.TestSupport.ObjectArrayConstructorDependency,?Tests.Unity.Configuration" ? /> ? </ typeAliases > ?
  • < containers > ? < container? name ="emptyArray" > ? < types > ? < type? type ="ArrayConstructor" > ? < typeConfig? > ? < constructor > ? < param? name ="loggers" ?parameterType ="ILoggerArray" > ? < array? /> ? </ param > ? </ constructor > ? </ typeConfig > ? </ type >
    Microsoft?patterns?&?practices?–?Unity?Application?Block?1.2?–?October?2008?33
    </ types > ? </ container >

    ?

?

  下面的配置文件使用dependency子元素描述了獲取指定類型的實(shí)例

?

代碼
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> < typeAliases > ?
  < typeAlias? alias ="ILogger" ?type ="Microsoft.Practices.Unity.TestSupport.ILogger,?TestSupport.Unity" ?/?<typeAliases > ?
    < container? name ="populatedArrayWithValues" >
      ? < types >
        ? < type? type ="ILogger" ?mapTo ="MockLogger" ?name ="logger1" > ? < lifetime? type ="singleton" ? /> ? </ type > ?
         < type? type ="ILogger" ?mapTo ="SpecialLogger" ?name ="logger2" > ? < lifetime? type ="singleton" ? /> ? </ type >
< type? type ="ArrayConstructor" > ?
          < typeConfig > ?
            < constructor > ?
              < param? name ="loggers" ?parameterType ="ILoggerArray" > ? < array > ? < dependency? name ="logger2" /> ? < dependency? name ="logger1" /> ? </ array > ? </ param > ? </ constructor > ? </ typeConfig > ? </ type > ?
  </ types > ?
</ container >

?

未完待續(xù)。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

微軟企業(yè)庫4.1學(xué)習(xí)筆記(二十五)Unity依賴注入模塊2


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 中山市| 方城县| 镇安县| 麻栗坡县| 吐鲁番市| 永春县| 渑池县| 怀安县| 弥渡县| 玉林市| 伊宁县| 宣汉县| 东港市| 新源县| 龙川县| 洛川县| 大同市| 任丘市| 民丰县| 连江县| 封开县| 彩票| 黄梅县| 常德市| 海盐县| 周至县| 安达市| 东明县| 泰来县| 义马市| 安达市| 静乐县| 桦甸市| 古交市| 永定县| 苍山县| 永兴县| 吴忠市| 新平| 云龙县| 台北县|