Reputation: 292465
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?
Upvotes: 3
Views: 1535
Reputation: 3726
The other way is:
var container = new UnityContainer();
container.AddNewExtension<Interception>()
.RegisterType<IFoo, Foo>()
.Configure<Interception>()
.SetInterceptorFor<IFoo>(new InterfaceInterceptor());
var foo = container.Resolve<IFoo>();
foo.Test();
And you create a class that inherits from HandlerAttribute and return an instance of type ICallHandler.Then add this attribute to the method to intercept.Something like this:
class MyAttribute : HandlerAttribute
{
override ICallHandler CreateHandler(IUnityContainer container)
{
return new TestCallHandler();
}
}
Interface IFoo
{
[MyAttribute]
void AMethod();
}
Upvotes: 3
Reputation: 14860
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();
Upvotes: 2