程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Unity Container 應用示例,unitycontainer

Unity Container 應用示例,unitycontainer

編輯:C#入門知識

Unity Container 應用示例,unitycontainer


一 項目引用Unity

右鍵項目引用-> 管理Nuget包->搜索unity->安裝Unity 和 Unity Interception Extension,如下圖所示.

二 創建基礎類

我們以商品查詢的數據層注入為例.

1.首先創建商品實體Model. 如果商品信息要被序列化,就要為該類添加Serializable特性.

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }

        public override string ToString()
        {
            return string.Format(" Product id:{0}\r\n Name:{1}\r\n Price:{2}\r\n",Id,Name,Price);
        }
    }

2.創建數據層接口及其實現類.

public interface IProductDao
    {
        Product Get(int id);
    }
public class ProductDao:IProductDao
    {
        public Product Get(int id)
        {
            #warning product info for test
            return new Product()
            {
                Id = id,
                Name = "Product"+id,
                Price = id*10
            };
        }
    }

3.直接創建實例

其實有了以上內容就可以調用查詢商品信息了.

static void Main( string[] args) 

        { 

IProductDao productDao= new ProductDao(); 

Product product = productDao.Get(5); 

Console.WriteLine(product.ToString()); 

Console.Read(); 

        }

三.使用Unity實現依賴注入

1.創建Unity配置文件

<? xml version= "1.0 "?> 
< configuration> 
  < configSections> 
    <!-- unity程序集--> 
    < section name= "unity " type =" Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> 
  </ configSections> 
  < unity xmlns= "http://schemas.microsoft.com/practices/2010/unity "> 
    <!-- 程序集和命名空間 --> 
    < assembly name= "DemoCache "/> 
    < namespace name= "DemoCache.Dao "/> 
    < namespace name= "DemoCache.Dao.Impl "/> 
    < container name= "Dao "> 
      <!-- 商品 --> 
      < register type= "IProductDao " mapTo= "ProductDao "></ register> 
    </ container> 
  </ unity> 
</ configuration>

2.創建UnityContainerManager類

創建UnityContainerManager讀取Unity.config配置.  完整代碼見附件,重點看一下從Unity.config讀取配置信息的方法:

private IUnityContainer LoadUnityConfig()
        {
            ////根據文件名獲取指定config文件
            string filePath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\Unity.config";
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };

            //從config文件中讀取配置信息
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
            var container = new UnityContainer();
            foreach (var item in unitySection.Containers)
            {
                container.LoadConfiguration(unitySection, item.Name);
            }

            return container;
        }

3.調用示例

static void Main( string[] args) 

        { 

IProductDao productDao = UnityContainerManager .Instance.Resolve<IProductDao >(); 
Product product = productDao.Get(8); 
Console.WriteLine(product.ToString()); 
Console.Read(); 

        }
四 使用Unity Interception實現日志 

1.創建ICallHandler接口實現類

新建類LogCallHandler類,實現接口ICallHandler. 每次調用相應方法時會自動將執行時間寫入日志.

public class LogCallHandler:ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //計時開始
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            //執行方法
            IMethodReturn result = getNext()(input, getNext);

            //計時結束
            stopWatch.Stop();

            //記錄日志

            var argumentsSb = new StringBuilder(input.MethodBase.Name);
            for (var i = 0; i < input.Arguments.Count; i++)
            {
                argumentsSb.AppendFormat("-{0}:{1}", input.Arguments.ParameterName(i), input.Arguments[i]);
            }
            LogHelper.LogInfo(string.Format("{2} 方法 {0},執行時間 {1} ms", argumentsSb, stopWatch.ElapsedMilliseconds,Msg));
            return result;
        }

        public int Order { get; set; }
        public string Msg { get; set; }
    }

2.創建特性

創建特性LogTime,它需要實現HandlerAttribute.

public class LogTimeAttributes:HandlerAttribute
    {
        public int Order { get; set; }
        public string Msg { get; set; }
        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new LogCallHandler()
            {
                Order = Order,
                Msg = Msg
            };
        }
    }

3.使用特性

[LogTimeAttributes (Order = 1,Msg = "查詢單個商品信息" )]

4.配置Unity.config

配置Unity Interception需要在unity節點下添加:

< sectionExtension 
type =" Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension,Microsoft.Practices.Unity.Interception.Configuration ">
</ sectionExtension >

然後在container節點下添加:

< extension type= "Interception " />

最後調整IProductDao的注冊節點:

< register type= "IProductDao " mapTo= "ProductDao "> 
        < interceptor type =" InterfaceInterceptor" /> 
        < policyInjection /> 
</ register>

調用處不用做調整,結果如下:

static void Main(string[] args) { var container = new UnityContainer().AddNewExtension<Interception>().RegisterType<IProductDao, ProductDao>(); container.Configure<Interception>().SetInterceptorFor<IProductDao>(new InterfaceInterceptor()); IProductDao productDao = container.Resolve<IProductDao>(); Product product = productDao.Get(8); Console.WriteLine(product); Console.Read(); }

代碼: http://files.cnblogs.com/files/janes/DemoCache.zip

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved