2

I'm looking for a way to hook up an interceptor to a method call based on a certain attribute using Ninject. Ninject offers the InterceptAttribute base class to do so which is neat, however I would like to achieve this with a custom attribute. The reason is that I want to decorate certain domain service interfaces with business related attributes, so I can't have any stuff tightly coupled to a framework in it.

Is this possible?

xvdiff
  • 2,179
  • 2
  • 24
  • 47

1 Answers1

2

You could derive from InterceptorRegistrationStrategy and override the Execute(IPlan plan) method (plus probably also RegisterClassInterceptors) to use your own attribute types instead of ninject's InterceptAttribute.

You would then need to register the implementation as a kernel component:

this.Kernel.Components.Add<IPlanningStrategy, MyInterceptorRegistrationStrategy>();

You'll probably also have to understand how InterceptorRegistrationStrategy, AutoNotifyInterceptorRegistrationStrategy and MethodInterceptorRegistrationStrategy work so you can create an implementation which works and is side-effect free. (this does not replace the interception extensions but rather just extends it).

There is also stackoverflow answer covering a custom strategy which might be useful: Ninject Intercept any method with certain attribute?

Or of course you could could use one of the other approaches to do interception:

  • with a binding, define interception for the whole type like Bind<IFoo>().To<Foo>().Intercept().With<MyInterceptor>() and have the MyInterceptor check whether it should intercept a given method or not.
  • use conventions API or write something like that yourself, search for all of your custom interception attributes and then use this syntax:
Kernel.InterceptAround<CustomerService>(
    s=>s.GetAllCustomers(),
    invocation =>logger.Info("Retrieving all customers..."),
    invocation =>logger.Debug("Customers retrieved"));

(also see Interception with ninject)

Community
  • 1
  • 1
BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68