Method-level attributed interception with Autofac

二次信任 提交于 2019-12-10 15:33:56

问题


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

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..
   }
}

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;
    }

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?


回答1:


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();
        }
    }

Registration would be something like this.

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


来源:https://stackoverflow.com/questions/28969429/method-level-attributed-interception-with-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!