简体   繁体   English

在Castle Windsor中,我可以注册一个Interface组件并获得实现的代理吗?

[英]In Castle Windsor, can I register a Interface component and get a proxy of the implementation?

Lets consider some cases: 让我们考虑一些情况:

_windsor.Register(Component.For<IProductServices>().ImplementedBy<ProductServices>().Interceptors(typeof(SomeInterceptorType));

In this case, when I ask for a IProductServices windsor will proxy the interface to intercept the interface method calls. 在这种情况下,当我请求IProductServices时,windsor将代理该接口以拦截该接口方法调用。 If instead I do this : 如果相反,我这样做:

_windsor.Register(Component.For<ProductServices>().Interceptors(typeof(SomeInterceptorType));

then I cant ask for windsor to resolve IProductServices, instead I ask for ProductServices and it will return a dynamic subclass that will intercept virtual method calls. 那么我不能要求Windsor解决IProductServices,而是要求ProductServices,它将返回一个动态子类,该子类将拦截虚拟方法调用。 Of course the dynamic subclass still implements 'IProductServices' 当然,动态子类仍实现“ IProductServices”

My question is : Can I register the Interface component like the first case, and get the subclass proxy like in the second case?. 我的问题是:是否可以像第一种情况一样注册Interface组件,并像第二种情况一样获得子类代理?

There are two reasons for me wanting this: 我想要这个有两个原因:
1 - Because the code that is going to resolve cannot know about the ProductServices class, only about the IProductServices interface. 1-因为要解析的代码无法知道ProductServices类,所以只能知道IProductServices接口。 2 - Because some event invocations that pass the sender as a parameter, will pass the ProductServices object, and in the first case this object is a field on the dynamic proxy, not the real object returned by windsor. 2-因为某些将发送者作为参数传递的事件调用将传递ProductServices对象,并且在第一种情况下,该对象是动态代理上的字段,而不是windsor返回的实际对象。 Let me give an example of how this can complicate things : Lets say I have a custom collection that does something when their items notify a property change: 让我举个例子说明如何使事情复杂化:假设我有一个自定义集合,该集合在其项通知属性更改时会执行某些操作:

private void ItemChanged(object sender, PropertyChangedEventArgs e)
    {
        int senderIndex = IndexOf(sender);
        SomeActionOnItemIndex(senderIndex);
    }

This code will fail if I added an interface proxy, because the sender will be the field in the interface proxy and the IndexOf(sender) will return -1. 如果添加接口代理,此代码将失败,因为发送方将是接口代理中的字段,并且IndexOf(sender)将返回-1。

Yes, you can: 是的你可以:

_windsor.Register(Component.For<ProductServices, IProductServices>()
   .Interceptors(typeof(SomeInterceptorType));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM