【问题标题】:Method-level attributed interception with Autofac使用 Autofac 进行方法级属性拦截
【发布时间】:2015-03-10 16:45:57
【问题描述】:

(这是一个与 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 中探索类似的方法。从我阅读和搜索的内容来看,似乎只有接口/类型级别的拦截可用。但我喜欢用这种属性控制的拦截行为来装饰单个方法的选项。有什么建议吗?

【问题讨论】:

    标签: dependency-injection autofac ioc-container


    【解决方案1】:

    当您说没有方法级别的拦截时,您是对的。 但是,当您使用 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>();
    

    【讨论】:

    • 看起来 Autofac 和 SimpleInjector 都在使用动态代理,并且没有对属性拦截的开箱即用支持。 Steven在这里提供了接口拦截的典型解决方案:stackoverflow.com/a/28969513/879655
    • @Calvin:更准确地说:Simple Injector 甚至不支持拦截。没有用于拦截的包或扩展。
    猜你喜欢
    • 2018-06-23
    • 2015-05-11
    • 2011-02-09
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多