首页 > 代码库 > Unity 的ICallHander在C#项目中实现注入
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(); }
Unity 的ICallHander在C#项目中实现注入
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。