天天看點

第九回 Microsoft.Practices.Unity.Interception實作基于資料集的緩存(針對六,七,八講的具體概念和配置的解說)

傳回目錄

概念

Microsoft.Practices.Unity.Interception是一個攔截器,它隸屬于Microsoft.Practices.Unity組成之中,主要完成AOP的功能,而實作AOP方法攔截(頁向切面)的基礎就是IoC,我們需要配置相關接口或者類型的IoC方式,然後在生産對象時,使用Unity的方法進行動态生産對象,這時,你的Interception攔截器也會起作用!

相關技術

IoC: 控制反轉(Inversion of Control,英文縮寫為IoC)是一個重要的面向對象程式設計的法則來削減計算機程式的耦合問題。 控制反轉一般又被稱為依賴注入(Dependency Injection,簡稱DI)。即将配置中的對象,動态注入到項目程式當中,使程式的某個功能可以動态進行切換。

AOP: 面向切面程式設計(也叫面向方面程式設計):Aspect Oriented Programming(AOP),是軟體開發中的一個熱點。利用AOP可以對業務邏輯的各個部分進行隔離,進而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。

一般用它來實作:日志記錄,性能統計,安全控制,事務處理,異常處理等等。

持久化方式

目前我的Project.UnityCaching元件支援Microsoft.Practices.EnterpriseLibrary.Caching和Redis兩種資料持久化的方式,前者也是Microsoft.Practices. EnterpriseLibrary企業庫的一部分,主要實作記憶體持久化(也可以實作檔案持久化),主要用在單台WEB伺服器上;後者可以單獨部署到一台或者多台伺服器上,主要實作分布式緩存,它是未來的大資料的一個方向。

鍵名組成

緩存解決方案名_命名空間_方法名,其中緩存解決方案名可以自己去配置,對應config中的CacheProjectName節點,而鍵對應的值采用字典類型,字典的鍵對應方法的各參數的組合。

涉及到的相關程式集

IoC基礎庫程式集

Redis基礎庫程式集

Project.Frameworks自封裝程式集

配置檔案中進行對IoC,AoP的配置

第九回 Microsoft.Practices.Unity.Interception實作基于資料集的緩存(針對六,七,八講的具體概念和配置的解說)
第九回 Microsoft.Practices.Unity.Interception實作基于資料集的緩存(針對六,七,八講的具體概念和配置的解說)
<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"  />
    <section name="RedisConfig" type="Redis.Client.RedisConfigInfo, Redis.Client"/>
  </configSections>

  <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60" MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false">
  </RedisConfig>

  <cachingConfiguration defaultCacheManager="ByteartRetailCacheManager">
    <cacheManagers>
      <add name="ByteartRetailCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" expirationPollFrequencyInSeconds="600" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
      <!--
          expirationPollFrequencyInSeconds:過期時間(seconds)
          maximumElementsInCacheBeforeScavenging:緩沖中的最大元素數量
          numberToRemoveWhenScavenging:一次移除的數量
      -->
    </cacheManagers>
    <backingStores>
      <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="NullBackingStore" />
    </backingStores>
  </cachingConfiguration>

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />

    <container>
      <!--泛型類型注入,資料倉儲服務注入,可以由ef,linq,ado,memory,file,nosql等方式實作-->
      <register type="IRepository.Core.IUnitOfWork,IRepository.Core" mapTo="NLayer_IoC_Demo.Entity.backgroundTestIoCEntities,NLayer_IoC_Demo.Entity" />
      <!--使用redis作為持久化存儲-->
      <!--<register type="IRepository.Core.IRepository`1,IRepository.Core" mapTo="Redis.Data.Core.RedisRepository`1,Redis.Data.Core" />-->
      <!--使用SQLSERVER作為持久化存儲-->
      <register type="IRepository.Core.IRepository`1,IRepository.Core" mapTo="NLayer_IoC_Demo.DATA.backgroundRepositoryBase`1,NLayer_IoC_Demo.DATA" />
      <register type="IRepository.Core.IExtensionRepository`1,IRepository.Core" mapTo="NLayer_IoC_Demo.DATA.backgroundRepositoryBase`1,NLayer_IoC_Demo.DATA" />

      <!-- AOP注入 -->
      <extension type="Interception" />
      <register type="NLayer_IoC_Demo.BLL.IUserService,NLayer_IoC_Demo.BLL" mapTo="NLayer_IoC_Demo.BLL.UserService,NLayer_IoC_Demo.BLL" >
        <!--接口攔截-->
        <interceptor type="InterfaceInterceptor" />
        <!--緩存注入-->
        <interceptionBehavior type="Project.UnityCaching.CachingBehavior,Project.UnityCaching"/>
      </register>

      <register type="NLayer_IoC_Demo.BLL.OrderService,NLayer_IoC_Demo.BLL" >
        <!--接口攔截-->
        <interceptor  type="VirtualMethodInterceptor" />
        <!--虛方法注入,生成派生類進行攔截,讓我們省去了建立接口的時間,不錯的選擇-->
        <!--Transparent Proxy Interceptor -->
        <!--它是注入所有的virutal method ,method,interface,但它的性能太差了-->
        <!--緩存注入-->
        <interceptionBehavior type="Project.UnityCaching.CachingBehavior,Project.UnityCaching"/>
      </register>

      <register type="Project.InterceptionBehaviors.IHandle, Project.InterceptionBehaviors" mapTo="Project.InterceptionBehaviors.StandardHandle, Project.InterceptionBehaviors">
        <!--接口攔截-->
        <interceptor type="InterfaceInterceptor" />
        <interceptionBehavior  type="NLayer_IoC_Demo.BLL.AOP.LoggerBehavior,NLayer_IoC_Demo.BLL" />
      </register>

    </container>
  </unity>

  <connectionStrings>
    <add name="backgroundTestIoCEntities" connectionString="metadata=res://*/background.csdl|res://*/background.ssdl|res://*/background.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=backgroundTestIoC;persist security info=True;user id=sa;password=zzl123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-NLayer_IoC_Demo-20141024091423;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-NLayer_IoC_Demo-20141024091423.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>      

View Code

使用時的相關注意要點

  1. Unity元件中引入了服務定位器ServiceLocator的概念,它可以使我們不引用目标程式集,而自動在bin目錄自動去定位。
  2. 對于Redis方式的緩存來說,進行緩存的實體類需要被聲明為Serializable特性。
  3. 實作IoC,AoP時,隻引用需要的程式集,而不用将所有Microsoft.Practices.Unity元件都引入,在程式進行編譯時,這些需要的程式集會自動添加到UI項目的BIN目錄。
  4. 方法攔截這塊有三種,但TransparentProxyInterceptor由于性能太差,我們并不提倡使用,項目中我們主要使用VirtualMethodInterceptor對于虛方法的攔截和InterfaceInterceptor對于接口的攔截,兩種方式各有好處,如果實作方式比較單一,可以直接使用虛方法注入,這樣可以省去寫接口的代碼量。

作者:倉儲大叔,張占嶺,

榮譽:微軟MVP

QQ:853066980

支付寶掃一掃,為大叔打賞!

第九回 Microsoft.Practices.Unity.Interception實作基于資料集的緩存(針對六,七,八講的具體概念和配置的解說)