依赖注入 – 使用Autofac进行方法级别的属性拦截

前端之家收集整理的这篇文章主要介绍了依赖注入 – 使用Autofac进行方法级别的属性拦截前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
(这是一个与 this one相关的问题,适用于SimpleInjector.我建议为每个IoC容器创建单独的问题.)

使用Unity,我可以快速添加基于属性拦截

public sealed class MyCacheAttribute : HandlerAttribute,ICallHandler
{
   public override ICallHandler CreateHandler(IUnityContainer container)
   {
        return this;
   }

   public IMethodReturn Invoke(IMethodInvocation input,GetNextHandlerDelegate getNext)
   {
      // grab from cache if I have it,otherwise call the intended method call..
   }
}

然后我这样注册Unity:

container.RegisterType<IPlanRepository,PlanRepository>(new ContainerControlledLifetimeManager(),new Interceptor<VirtualMethodInterceptor>(),new InterceptionBehavior<PolicyInjectionBehavior>());

在我的存储库代码中,我可以选择性地装饰要缓存的某些方法(具有可以为每个方法单独定制的属性值):

[MyCache( Minutes = 5,CacheType = CacheType.Memory,Order = 100)]
    public virtual PlanInfo GetPlan(int id)
    {
        // call data store to get this plan;
    }

我在Autofac中探索类似的方法.从我读取和搜索内容看起来只有接口/类型级别拦截可用.但我希望能够选择使用这种类型的属性控制拦截行为来装饰各个方法.有什么建议吗?

解决方法

当你说没有方法拦截时,你是对的.
但是,当您使用write类型拦截器时,您可以访问正在调用方法.注意:这依赖于Autofac.Extras.DynamicProxy2包.

public sealed class MyCacheAttribute : IInterceptor
    {

        public void Intercept(IInvocation invocation)
        {
            // grab from cache if I have it,otherwise call the intended method call..

            Console.WriteLine("Calling " + invocation.Method.Name);

            invocation.Proceed();
        }
    }

注册将是这样的.

containerBuilder.RegisterType<PlanRepository>().As<IPlanRepository>().EnableInterfaceInterceptors();
     containerbuilder.RegisterType<MyCacheAttribute>();

猜你在找的设计模式相关文章