简体   繁体   中英

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. 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. Of course the dynamic subclass still implements 'IProductServices'

My question is : Can I register the Interface component like the first case, and get the subclass proxy like in the second case?.

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. 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. 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.

Yes, you can:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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