Castle Windsor: Register two interfaces as one singleton with interception
Following my previous question regarding Unity ( Unity: Register two interfaces as one singleton with interception ), I tried to do the same with Castle Windsor:
I have a class that implements two interfaces, and I want to apply interception to the class's methods. I'm using forwarded types to do this and have come up with the following code:
public interface I1
{
void Method1();
}
public interface I2
{
void Method2();
}
public class C : I1, I2
{
public void Method1() {}
public void Method2() {}
}
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocatio开发者_运维技巧n)
{
Console.WriteLine("Entering " + invocation.Method.Name);
invocation.Proceed();
Console.WriteLine("Leaving " + invocation.Method.Name);
}
}
public static void CastleWindsorTest()
{
var container = new WindsorContainer();
container.Register(
Component.For<LogInterceptor>(),
Component.For<I2, I1>().ImplementedBy<C>()
.Interceptors(new InterceptorReference(typeof(LogInterceptor))).First
);
container.Resolve<I2>().Method2();
container.Resolve<I1>().Method1();
}
The above code leads to the following output:
Entering Method2
Leaving Method2
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Castle.Proxies.I2Proxy' to type 'I1'.
at Castle.Windsor.WindsorContainer.Resolve[T]() in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:line 872
at BlahMain.Program.CastleWindsorTest()
at BlahMain.Program.Main(String[] args)
Removing the ".Interceptors" line causes the code to run without problems (but of course my interception code is not invoked). If I remove the ".Interceptors" line and instead decorate class C with "[Interceptor(typeof(LogInterceptor))]", I get the same output as above (i.e. Entering/Leaving Method2, followed by the exception).
Is there a way to achieve this?
I hope I understood what you meant. I tried to use:
var container = new WindsorContainer();
container.Register(
Component.For<LogInterceptor>(),
Component.For<C, I2, I1>().ImplementedBy<C>()
.Interceptors(new InterceptorReference(typeof(LogInterceptor))).First
);
container.Resolve<I2>().Method2();
container.Resolve<I1>().Method1();
Now the application doesn't crash with an exception, but my logging code is not called. The output I get is:
Method2 0
Method1 2
精彩评论