dlongest
dlongest

Reputation: 11

Different Castle interceptor instances for different dependencies

I have an Castle Windsor interceptor that I want to use for two different interfaces (just call them IOne and ITwo). Similar to this post http://thatextramile.be/blog/2009/07/protecting-your-application-from-remote-problems/ I want the interceptor to be a singleton with respect to the same interface, but be a different instance for each interface. Obviously registering the interceptor as singleton causes the same instance to be reused across all instances of IOne and ITwo. I need the interceptors to behave this way because I need them to preserve state for all calls through that interface, but they need to be distinct from each other.

I've come across lots of possible ways to approach this, but since I'm not an expert on Windsor, what is the preferred way to handle this situation?

Upvotes: 1

Views: 310

Answers (2)

gregsdennis
gregsdennis

Reputation: 8428

An alternative approach is to make the interceptor generic. Then you can specify the interceptor with the generic argument of your interface.

public class MyInterceptor<T> : IInterceptor
{
    ...
}

Then register like this

container.Register(Component.For<IOne>()
                            .ImplementedBy<OneImplementation>()
                            .Interceptors<MyInterceptor<IOne>>());
container.Register(Component.For<ITwo>()
                            .ImplementedBy<TwoImplementation>()
                            .Interceptors<MyInterceptor<ITwo>>());

.Net will recognize MyInterceptor<IOne> and MyInterceptor<ITwo> as separate classes, and so Windsor will create different singleton instances for them.

Of course, this only works if you're making the interceptor. If it's in some library that you don't have access to, then your out of luck with this approach.

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38508

Documentation says it's recommended to use the interceptors with transient lifecycle.

Make interceptors transient

It is strongly advised that you always make your interceptors transient. Since interceptors can intercept multiple components with various lifestyles it's best if their own lifespan is no longer than the component they intercept. So unless you have a very good reason not to, always make them transient.

I suggest refactoring the shared data interaction to another interface then use that as singleton.

Upvotes: 2

Related Questions