Search code examples
c#inversion-of-controlunity-containerunity-interception

Why is my custom call handler not called?


I'm trying to understand how to use call handlers with Unity. Here's the code I have so far:

void Main()
{
    var container = new UnityContainer();
    container.AddNewExtension<Interception>()
             .Configure<Interception>()
             .AddPolicy("TestPolicy")
             .AddCallHandler(new TestCallHandler());
    container.RegisterType<IFoo, Foo>();
    var foo = container.Resolve<IFoo>();
    foo.Test();
}

interface IFoo
{
    void Test();
}

class Foo : IFoo
{
    public void Test()
    {
        "Foo.Test()".Dump();
    }
}

class TestCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate  getNext)
    {
        Console.WriteLine("[Interceptor] Calling {0}.{1}", input.MethodBase.DeclaringType.FullName, input.MethodBase.Name);
        return getNext()(input, getNext);
    }

    public int Order { get; set; }
}

But TestCallHandler.Invoke is never called, it just calls Foo.Test directly. What am I missing?


Solution

  • Register both the type and the handler and add an interceptor with a PolicyInjectionBehavior.

    var container = new UnityContainer();
    container.AddNewExtension<Interception>()
             .RegisterType<TesCallHandler>()
             .RegisterType<IFoo, Foo>(new Interceptor<TransparentProxyInterceptor>(),
                 new InterceptionBehavior<PolicyInjectionBehavior>())
             .Configure<Interception>()
             .AddPolicy("TestPolicy")
             .AddCallHandler(new TestCallHandler());
    var foo = container.Resolve<IFoo>();
    foo.Test();