views:

458

answers:

1

I am using Castle Windsor in my own implementation of the Resolver Pattern. I have two implementations of a service MethodAService and MethodBService that both implement IMethodService. I am using "Convention Over Configuration" when bootstrapping Windsor in. How can I tell Castle Windsor to use always use MethodAService in one instance (Debug, Release, etc.), but in the other, use MethodBService. Thank you for your time!

+2  A: 

Here's one way to do it, using IHandlerSelector:

public class DebugHandlerSelector: IHandlerSelector {
    private readonly Type serviceType;
    private readonly Type debugImplementation;
    private readonly Type releaseImplementation;

    public DebugHandlerSelector(Type serviceType, Type debugImplementation, Type releaseImplementation) {
        this.serviceType = serviceType;
        this.debugImplementation = debugImplementation;
        this.releaseImplementation = releaseImplementation;
    }

    public bool HasOpinionAbout(string key, Type service) {
        return service == serviceType;
    }

    public IHandler SelectHandler(string key, Type service, IHandler[] handlers) {
        return handlers.First(h => h.ComponentModel.Implementation == 
#if DEBUG
            debugImplementation
#else
            releaseImplementation
#endif                    
            );
    }
}

Sample usage:

container.Kernel.AddHandlerSelector(new DebugHandlerSelector(typeof(IMethodService), typeof(MethodAService), typeof(MethodBService)));
Mauricio Scheffer
How do I make this not dependent on IHandlerSelector?
Daniel A. White
Or on Castle Windsor for that matter?
Daniel A. White
I actually now really like this. I refactored it to use Generics instead of the 3 typeof's in the constructor call!
Daniel A. White