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

项目包引用: 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();
        }

  

posted @ 2014-08-22 17:28  violence  阅读(1609)  评论(4编辑  收藏  举报