Add Interception Behavior on Registering Event

Feb 3, 2011 at 1:42 PM


Is it possible to add an interception behavior during the Registering event of an extension?

Let's say I have this code:

public class DefaultInterceptorInterceptionExtension : PolicyInjectionInterceptionExtension
	protected override void Initialize()

		this.Container.Registering += delegate(Object sender, RegisterEventArgs e)
			//here: add an interceptor

I know how to add interceptors through RegisterType, but, if I do that, my application would enter a loop.

Any ideas?



Feb 3, 2011 at 4:29 PM

You can easily do this, but it's a little roundabout, since, as you say, if you just call RegisterType again you'll end up in an infinite loop.

Everything is configured under the hood by adding Policy objects to an internal PolicyList. InterceptionMember objects (like InjectionConstructor or Interceptor) generate policies. You have direct access to the container's policy list inside an extension.

So, what I'd try looks like this:

this.Container.Registering += (sender, e) =>
        var i = new Interceptor<VirtualMethodInterceptor>();
        i.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);

(ShouldIntercept is a method you would write to determine if you actually want to add the interceptor or not).

You can do the same thing to set up anything you can do via the RegisterType API, so you can do the same thing for InterceptionBehaviors, properties, whatever. Also, since Unity uses a "last one in wins" configuration model, you could actually overwrite things like configured constructors if you so desire.


Hope this helps,