使用Unity实现AOP拦截器时,自动完成注册的处理

  • 使用Unity实现AOP拦截器时,自动完成注册的处理已关闭评论
  • 138 次浏览
  • A+
所属分类:.NET技术
摘要

说明:这里只是VirtualMethodInterceptor拦截器的处理,下面代码中用到的ViewModelCommandBehavior是对IInterceptionBehavior接口的实现

说明:这里只是VirtualMethodInterceptor拦截器的处理,下面代码中用到的ViewModelCommandBehavior是对IInterceptionBehavior接口的实现

主要就是用反射获取到相应的方法来执行指定的操作

问题:通常是用下面注释掉的 interception.RegisterSingleton 来注册,但是当需要注册的类很多或者不确定时会很不方便,所以改用下面的方法来自动完成相关类的注册

        void SetInterceptor()         {             IUnityContainer unityContainer = new UnityContainer();             IUnityContainer interception = unityContainer.AddNewExtension<Interception>();             //interception.RegisterSingleton<CustomViewModel>(new Interceptor<VirtualMethodInterceptor>(), new InterceptionBehavior<ViewModelCommandBehavior>());             //return;             Assembly assem = Assembly.GetExecutingAssembly();             var types = assem.ExportedTypes;             foreach (Type item in types)             {                 //具体做哪些限制根据实际情况来                 if (item.IsClass && typeof(ViewModelBase).IsAssignableFrom(item))                 {                     //这里可以加一些其它的限制,目前值用于CustomViewModel                     if (item.FullName == typeof(CustomViewModel).FullName)                     {                         //可以参考上面的RegisterSingleton方法调用,这里的RegisterSingleton是用的扩展类中的扩展方法                         //所以在查找方法时是直接在扩展类中找的,而且因为扩展方法是静态方法所以Invoke执行时对象可以设置为null                         var method = typeof(UnityContainerExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public)                             .Where(x => x.Name == "RegisterSingleton" && x.IsGenericMethod == true && x.GetGenericArguments().Length == 1                             && x.GetParameters().Length == 2 && x.GetParameters()[1].ParameterType.FullName == typeof(InjectionMember[]).FullName).FirstOrDefault();                         if (method != null)                         {                             method = method.MakeGenericMethod(new Type[] { item });                             InjectionMember[] injectionMembers = new InjectionMember[2];                             injectionMembers[0] = new Interceptor<VirtualMethodInterceptor>();                             injectionMembers[1] = new InterceptionBehavior<ViewModelCommandBehavior>();                             object[] pars = new object[2];                             pars[0] = interception;                             pars[1] = injectionMembers;                             method.Invoke(null, pars);                         }                     }                 }             }         }