在前面的章节中,我们了解了如何通过DynamicProxy来实现对接口调用的拦截,在今天的实例中,我们将会看到一个具体的应用。
在我们所开发软件系统中,权限鉴别是一个非常重要的部分。通常在具体的需要权限访问的方法中,我们需要加入大段的代码来校验当前用户是否有权限操作当前的方法中的一些环节,不仅如此,我们甚至于还需要在方法的签名中加入相关的可代表用户身份的信息,例如:
void DoOperationxx(string userId,string param1,string param2)..
在这个方法中,可能实际需要用到的参数只是"string param1,string param2",但是我们加入userId 的参数,纯粹只是为了鉴别当前用户是否有权限访问而以,导致我们的代码显得非常的冗余。
我们知道AOP的本质是对方法进行拦截,那么,我们能否在方法调用前组织一些用于鉴权的信息进行校验,校验通过后,再进入实际的调用过程呢?这个便是我们在这篇文章中要讨论的具体内容。
先来理顺一下思路及相关概念:
- 上下文信息(IContextInfo):我们将鉴别权限所需要的相关信息定义为上下文信息
- 上下文生成工厂(IContextInfoFactory):从名称上我们可以知道这个是用于生成上下文
- 上下文校验器(IContextValidate):用于对当前的上下文进行检查,判断是否有效
最后,我们还需要给方法一个描述,我们希望在方法上加入一个标签,来描述这个方法用哪个校验器来进行上下文校验,例如:
[ContextValidate("UserValidate")]
void DoOperationxx(string param1,string param2)
在上面的方法中,会告知系统,在调用这个方法前,先用“UserValidate” 所标识的上下文验证器来校验当前的上下文是否有效。我们来看看与上下文相关的一些类型的定义:
- /// <summary>
- /// 打在方法上的上下文验证器标签
- /// </summary>
- [AttributeUsage(AttributeTargets.Method)]
- public class ContextValidateAttribute:Attribute
- {
- private readonly string validateKey;
- public string ValidateKey
- {
- get { return validateKey; }
- }
- public ContextValidateAttribute(string validateKey)
- {
- this.validateKey = validateKey;
- }
- }
- //上下文信息
- public interface IContextInfo
- {
- }
- //上下文工厂
- public interface IContextInfoFactory
- {
- IContextInfo CreateContextInfo(MethodInfo methodInfo);
- }
- /// <summary>
- /// 上下文验证操作接口
- /// </summary>
- public interface IContextValidate
- {
- void Validate(IContextInfo contextInfo, MethodInfo methodInfo);
- }
根据上文相关的定义,我们需要建立这样的一种应用方式:在调用方法之前先进行拦截,用IContextInfoFactory成来生上下文,然后由识别当前方法上面的标注信息,交由相应的上下文验证器进行验证,最后,在验证无误时,再交由实际的方法来进行调用并返回,举例来说:如果我们有这样的定义:
- //接口定义
- public interface IOperation
- {
- .......
- }
- //接口实现
- public class Operation:IOperation
- {
- ......
- }
在调用时,我们会依据接口(IOperation)生成Proxy对象,在进行具体的方法调用前,我们会先设方获取真实的Operation对象,检查真实对象当前的方法标签上是否有ContextValidateAttribute标记,如果有的话,我们先设法取得上下文信息,然后,设法获取ContextValidateAttribute所标记的验证器,对上下文进行验证,如果验证出错,则抛出异常,验证通过,则调用直实对象的相应的方法并获得返回值。为了简化这一系列的过程,我们借助Castle的WindsorContainer这个IoC容器来完成装载及获得对象的工作,因此,在我们的方法拦截器中,我们假定上下文验证器及我们要调用的对象都在IoC容器中。
- public class LocalProxyInterceptor : IInterceptor
- {
- private readonly IContextInfoFactory contextInfoFactory;
- private readonly IWindsorContainer container;
- private readonly string serviceKey;
- public void Intercept(IInvocation invocation)
- {
- //检测真实的对象在容器中是否存在,如果存在,获取对象的实例及类型
- if (!container.Kernel.HasComponent(serviceKey))
- throw new NotFoundInstanceException(serviceKey);
- object instance = container[serviceKey];
- Type instanceType = instance.GetType();
- //组合调用的参数类型,用于查找到实例中对应的方法
- List<Type> paramTypes = new List<Type>();
- foreach (ParameterInfo paramInfo in invocation.Method.GetParameters())
- paramTypes.Add(paramInfo.ParameterType);
- const BindingFlags FindFlags =
- BindingFlags.FlattenHierarchy |
- BindingFlags.Instance |
- BindingFlags.NonPublic |
- BindingFlags.Public;
- MethodInfo methodInfo =
- instanceType.GetMethod(invocation.Method.Name,
- FindFlags, null, paramTypes.ToArray(), null);
- if (methodInfo == null)
- throw new NotFoundMethodException(invocation.Method.Name);
- //如果在实例的方法指明了上下文验证器,则生成对应的上下文信息并进行验证
- if (Attribute.IsDefined(methodInfo, typeof (ContextValidateAttribute)))
- {
- ContextValidateAttribute validateAttr =
- (ContextValidateAttribute)
- Attribute.GetCustomAttribute(methodInfo,
- typeof (ContextValidateAttribute));
- if (!container.Kernel.HasComponent(validateAttr.ValidateKey))
- throw new NotFoundInstanceException(validateAttr.ValidateKey);
- IContextValidate contextValidate =
- (IContextValidate) container[validateAttr.ValidateKey];
- contextValidate.Validate(
- contextInfoFactory.CreateContextInfo(methodInfo), methodInfo);
- }
- //调用容器中实例相对应的方法,并设置返回值
- invocation.ReturnValue =
- methodInfo.Invoke(instance,invocation.Arguments);
- }
- public LocalProxyInterceptor(string serviceKey,
- IWindsorContainer container, IContextInfoFactory contextInfoFactory)
- {
- this.contextInfoFactory = contextInfoFactory;
- this.serviceKey = serviceKey;
- this.container = container;
- }
- }
有了拦截器,我们再来定义Proxy工厂接口及实现
- //Proxy对象工厂的接口定义
- public interface ILocalProxyFactory
- {
- //根据指定的容器Key、上下文生成工厂来建立Proxy对象
- T CreateProxy<T>(string serviceKey,IContextInfoFactory contextInfoFactory);
- }
- //Proxy对象工厂的接口实现
- public class LocalProxyFactory:ILocalProxyFactory
- {
- private readonly IWindsorContainer container;
- public LocalProxyFactory(IWindsorContainer container)
- {
- this.container = container;
- }
- public T CreateProxy<T>(string serviceKey, IContextInfoFactory contextInfoFactory)
- {
- IInterceptor _interceptor =
- new LocalProxyInterceptor(serviceKey, container, contextInfoFactory);
- ProxyGenerator proxyGenerator = new ProxyGenerator();
- return proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(_interceptor);
- }
- }
接下来,我们来做一下完整的实现,先来实现上下文的接口
- public class ContextInfo:IContextInfo
- {
- private readonly string userName;
- public string UserName
- {
- get { return userName; }
- }
- public ContextInfo(string userName)
- {
- this.userName = userName;
- }
- }
- public class ContextInfoFactory:IContextInfoFactory
- {
- private string userName;
- public string UserName
- {
- get { return userName; }
- set { userName = value; }
- }
- public ContextInfoFactory(string userName)
- {
- this.userName = userName;
- }
- public IContextInfo CreateContextInfo(MethodInfo methodInfo)
- {
- return new ContextInfo(userName);
- }
- }
- //实现一个简单的上下文验证器,判断用户是否为 "Roger",如果不是则抛异常
- public class UserValidate:IContextValidate
- {
- public void Validate(IContextInfo contextInfo, MethodInfo methodInfo)
- {
- if (contextInfo == null || !(contextInfo is ContextInfo))
- throw new InvalidContextInfoException();
- ContextInfo info = (ContextInfo) contextInfo;
- if (info.UserName != "Roger")
- throw new Exception("UserName Invalid");
- }
- }
再来完成一个简单的调用服务
- public interface IShowMessage
- {
- void Calc(int x, int y);
- }
- public class ShowMessage:IShowMessage
- {
- //指示调用当前的方法前必须通过"UserValidate"进行上下文验证
- [ContextValidate("UserValidate")]
- public void Calc(int x, int y)
- {
- Console.WriteLine("Client Call {0} + {1}!", x, y);
- }
- }
最后,我们来看看Main函数部分的程序
- static void Main()
- {
- WindsorContainer container = new WindsorContainer();
- //将ShowMessage服务装入IoC容器中
- container.AddComponent("ShowMessage",
- typeof (IShowMessage), typeof (ShowMessage));
- //将UserValidate这个上下文验证器装入IoC容器中
- container.AddComponent("UserValidate",
- typeof (IContextValidate), typeof (UserValidate));
- try
- {
- //建立上下文工厂
- ContextInfoFactory contextInfoFactory = new ContextInfoFactory("Roger");
- //建立Propxy对象工厂
- ILocalProxyFactory localProxyFactory = new LocalProxyFactory(container);
- //获到IShowMessage的Proxy对象
- IShowMessage showMessage =
- localProxyFactory.CreateProxy<IShowMessage>("ShowMessage", contextInfoFactory);
- showMessage.Calc(300, 400);
- //改变当前用户的名称,让验证器抛异常
- contextInfoFactory.UserName = "Windy";
- showMessage.Calc(300, 400);
- }
- catch(Exception ex)
- {
- Console.WriteLine("ExceptionType:{0},ExceptionMessage:{1}",
- ex.GetType(), ex.Message);
- }
- Console.ReadLine();
- }
运行结果如下:
本文始发于:http://www.rogertong.cn/article.asp?id=28
Ps: 周一要去上海一趟,上海的兄弟们记得请喝酒啊。