Standalone Unity Interception and Call Handler Attributes

May 28, 2010 at 8:39 PM
Edited May 28, 2010 at 8:42 PM
I've found a nifty way of getting HandlerAttributes to kick in the the standalone interception. It took my a while to figure it out, but since I have, I thought I'd share...

Basically, I was trying to use the Standalone interception to wrap a class and call Call Handlers specified by call handler attributes. Something along the lines of this:

// get a MyClass object
MyClass wrappedInstance = Intercept.NewInstance<MyClass>(..what to do here?..)

// call the method and any call handlers specified by HandlerAttributes along the way...
wrappedInstance.MyMethod("hello world");

class MyClass

public virtual string MyMethod(string input)
     // do something here, but I want it to be intercepted by the call handler


// my call handler attribute...
class MyCustomCallHandlerAttribute : HandlerAttribute
public override ICallHandler CreateHandler(IUnityContainer container)
return new MyCustomCallHandler();

// my call handler...
public class MyCustomCallHandler : ICallHandler
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
     // do stuff here each time My Method is called
     return getNext()(input, getNext);

It took me little while to figure it out with the standalone unity stuff, but the following method intercepts using Virtual Method Interception and applies the PolicyInjectionBehavior with AttributeDrivenPolicy. These are the two vital bits that are needed to make the Call Handlers get called when the method is called:

public class MyUnityInterceptor
	public static T Get<T>() where T : class
		VirtualMethodInterceptor interceptor = new VirtualMethodInterceptor();

		CurrentInterceptionRequest request = new CurrentInterceptionRequest(interceptor, typeof(T), typeof(T));

		InjectionPolicy[] policies = new InjectionPolicy[] { new AttributeDrivenPolicy() };

		PolicyInjectionBehavior behaviour = new PolicyInjectionBehavior(request, policies, null);

		return Intercept.NewInstance<T>(
			new IInterceptionBehavior[] { behaviour },

... so in this example, create my class like this:

MyClass wrappedMyClass = MyUnityInterceptor.Get<MyClass>();

... then call the method as normal.

wrappedMyClass.MyMethod("hello world");

Feb 24, 2011 at 11:17 PM

WoW this is what I need exactly. Big thanks to Dave for sharing the info.

Nov 15, 2012 at 3:26 PM

Thanks a billion!... This makes my code a lot simpler!