使用Autofac进行方法级别的属性拦截 [英] Method-level attributed interception with Autofac

查看:414
本文介绍了使用Autofac进行方法级别的属性拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这是与这一个有关的问题,该问题用于SimpleInjector建议我为每个IoC容器分别创建问题.)

(this is a related question to this one which is for SimpleInjector. I was recommended to create separate questions for each IoC container.)

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

With Unity, I'm able to quickly add an attribute based interception like this

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注册:

Then I register with Unity this way:

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

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

In my repository code, I can selectively decorate certain methods to be cached (with attribute values that can be customized individually for each method) :

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

我正在用 Autofac 探索类似的方法.从我阅读和搜索的内容来看,似乎只有接口/类型级别的拦截可用.但是我很乐意用这种类型的属性控制的拦截行为来装饰单个方法.有什么建议吗?

I'm exploring similar ways to do this in Autofac. From what I read and searched looks like only interface/type level interception is available. But I would love the option of decorating individual methods with this type of attribute controlled interception behavior. Any advise?

推荐答案

当您说没有方法级别的拦截时,您是对的. 但是,当您使用编写类型拦截器时,您可以访问被调用的方法. 注意:这依赖于Autofac.Extras.DynamicProxy2程序包.

You're right when you say there's no method level interception. However, when you use write a type interceptor you have access to the method that is being invoked. Note: this relies on the Autofac.Extras.DynamicProxy2 package.

    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进行方法级别的属性拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆