Search code examples
c#unity-containerunity-interception

Microsoft Unity: Interception not working when using BuildUp instead of Resolve


I am using Microsoft Unity 2.0 and the interception extension is not working as expected.

Consider these two lines of code:

MyUnityContainer.Configure<Interception>().SetDefaultInterceptorFor<MyType>(new VirtualMethodInterceptor());
var someObject = MyUnityContainer.BuildUp<MyType>(anObject);

These two lines don't get you the dynamic proxy you'd expect for someObject! How can one make interception work for such a scenario?


Solution

  • This page explains that you cannot use virtual interception using BuildUp since it can only be applied when the object is created (since a subclass of the target object is dynamically generated):

    Interception only happens on virtual methods. You must set up interception at object creation time and cannot intercept an existing object.