[英]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: 在我先前关于Unity的问题( Unity:将两个接口注册为具有拦截功能的一个单例 )之后,我尝试对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 invocation)
{
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). 删除“ .Interceptors”行会使代码运行没有问题(但当然不会调用我的拦截代码)。 If I remove the ".Interceptors" line and instead decorate class C with "[Interceptor(typeof(LogInterceptor))]", I get the same output as above (ie Entering/Leaving Method2, followed by the exception). 如果我删除“ .Interceptors”行,而用“ [[Interceptor(typeof(LogInterceptor))]””装饰类C,则会得到与上述相同的输出(即Enter / LeaveMethod2,后跟异常)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.