模块介绍
PolicyInjection PolicyInjection模块
简单示例
主方法业务类自定义CallHandler自定义LogHandlerAttribute ICallHandler
Invoke方法Order调用具体方法inputgetNextIMethodReturn抛出异常
基于Enterprise Library6.0版本
模块介绍
PolicyInjection
PolicyInjection模块是在企业库3.0才正式引入的模块,简称PIAB(Policy Injection Application Block),这个模块的主要功能是方便我们在项目开发中进行AOP(面向切面编程),以简化开发内容。
PolicyInjection模块
简单示例
演示利用PolicyInjection模块在方法执行前和后打印调用日志
主方法
IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
PolicyInjector policyInjector = new PolicyInjector(configurationSource);
PolicyInjection.SetPolicyInjector(policyInjector);
Operation o = policyInjector.Create<Operation>();
o.Run();
Console.Read();
业务类
业务类必须继承自MarshalByRefObject。
public class Operation : MarshalByRefObject
{
[LogHandler]
public void Run()
{
Console.WriteLine("执行了方法1");
}
}
自定义CallHandler
public class LogHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine("方法前执行");
IMethodReturn result = getNext().Invoke(input, getNext);
Console.WriteLine("方法后执行");
return result;
}
public int Order
{
get;
set;
}
}
自定义LogHandlerAttribute
对方法拦截有两种方式,Attribute拦截,Configuration拦截.示例采用第一种方式. 定义后,只要在方法上标明该Attribute则会调用响应的LogHandler.
public class LogHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new LogHandler();
}
}
ICallHandler
Invoke方法
invoke方法用于对具体拦截方法做相应的处理
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
Order
多个Handler调用的先后顺序
private int _order = 0;
public int Order
{
get
{
return _order;
}
set
{
_order = value;
}
}
调用具体方法
var result = getNext()(input, getNext);
这个参数中封装了已拦截的方法、方法的参数等有用的信息 inputs 传入的参数值和参数类型。 InvocationContext MethodBase 注入的方法 Target 注入的类
getNext
一个委托,用于调用拦截的方法,通过这个委托我们可以很好的控制我们需要在拦截了具体方法后如何进行具体的业务逻辑操作。
IMethodReturn
调用后的返回值 Exception 调用中的异常 InvocationContext Outputs 输出参数 ReturnValue 返回值
抛出异常
if(result.Excepiton!=null)
{
return input.CreateExceptionMethodReturn(new Exception("Permission Denied"));
}
转载请注明原文地址: https://ju.6miu.com/read-673380.html