I have a service with two different implementations and I would like to inject into the controllers constructor, depends on a criteria (at the moment the criteria is a simple value stored in session).
Here is what I got now...
Service interface:
public interface IService
{
string GetSampleText();
}
Implementation #1:
public class FirstService : IService
{
string GetSampleText()
{
return "First Service";
}
}
Implementation #2:
public class SecondService : IService
{
string GetSampleText()
{
return "Second Service";
}
}
Registration in a Windsor installer class:
container.Register(AllTypes
.FromAssemblyInDirectory(new AssemblyFilter(HttpRuntime.BinDirectory))
.BasedOn<IService>()
.WithService.FromInterface()
.Configure(c => c.LifeStyle.Transient));
container.Kernel.AddHandlerSelector(new ServiceHandlerSelector());
I have implemented an IHandlerSelector:
public class ServiceHandlerSelector : IHandlerSelector { ... }
In the HasOpinionAbout method of this IHandlerSelector implementation I can decide which handler will be selected in the SelectHandler method (depends on the value from session).
Then the constructor injection is working fine on the controllers:
public MyController(IService service) { ... }
So I got a working solution, but I am not sure if it is the best way to do this.
Opinions? Suggestions?
Many thanks.