4

(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?

Community
  • 1
  • 1
Calvin
  • 1,153
  • 2
  • 14
  • 25

1 Answers1

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>();
gaunacode.com
  • 365
  • 2
  • 13
  • Looks like both Autofac and SimpleInjector are using Dynamic proxy and there is no out-of-box support for attributed interception. Steven provided the typical solution for interface interception here: http://stackoverflow.com/a/28969513/879655 – Calvin Mar 11 '15 at 16:34
  • @Calvin: To be more precise: Simple Injector doesn't even support interception. There is no package or extensions for doing interception. – Steven Mar 11 '15 at 21:37