码迷,mamicode.com
首页 > 其他好文 > 详细

Unity 的ICallHander在C#项目中实现注入

时间:2014-08-22 17:43:29      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   log   

项目包引用: Install-Package Unity.Interception

创建项目的接口和其实类:

public interface ICalculator
{
double CalculateAdd(double a, double b); 
double CalculateMultiply(double a, double b);
double CalculateMinus(double a, double b);
double CalculateDevide(double a, double b);
}

[LoggerIndicate]
public class Calculator:ICalculator
{
public double CalculateAdd(double a, double b) { return a + b; }
public double CalculateMultiply(double a, double b) { return a * b; }
public double CalculateMinus(double a, double b) { return a - b; }
public double CalculateDevide(double a, double b) { return a / b; }
}

创建一个方法注入的类,这个类必须实现ICallHander接口

    public class LoggerHandler : ICallHandler
    {        
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var traceId = System.Guid.NewGuid().ToString();
            TimeRecorder tr = new TimeRecorder();
            var result = getNext()(input, getNext);
            tr.Dispose();
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Call {0} (", input.MethodBase.Name);            
            foreach (var parameter in input.Arguments)
            {
                sb.Append(parameter.ToString()).Append(",");
            }
            sb.Append(")");
            sb.AppendFormat(" takes {0}ms", tr.ElapsedMilliseconds);
            Console.WriteLine(sb.ToString());
            return result;
        }

        public int Order { get; set; } //用来控制执行顺序
    }

创建属性来标是否需要注入

 public class LoggerIndicateAttribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(IUnityContainer container) {
            return new LoggerHandler();
        }
    }

最后测试

 static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.AddNewExtension<Interception>();
            container.RegisterType<ICalculator, Calculator>()
              .Configure<Interception>()
              .SetInterceptorFor<ICalculator>(new InterfaceInterceptor());

            // Resolve
            ICalculator calc = container.Resolve<ICalculator>();


            var d = calc.CalculateAdd(1, 2);
            d = calc.CalculateMinus(23, 3);
            Console.Read();
        }

  

Unity 的ICallHander在C#项目中实现注入

标签:style   blog   color   os   io   for   ar   div   log   

原文地址:http://www.cnblogs.com/sgciviolence/p/3929916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!