I have 2 implementations of the same interface and want to use implementation1 if the user is logged in or implementation2 if the user is not logged in. How can I configure this with castle windsor?
You could add a handler selector, which would be able to select between available implementations depending on e.g. whether Thread.CurrentPrincipal
was set (or HttpContext.Current.Request.IsAuthenticated
in ASP.NET/MVC if I remember correctly).
The handler selector would probably look somewhat like this:
public class MyAuthHandlerSelector : IHandlerSelector
{
public bool HasOpinionAbout(string key, Type service)
{
return service == typeof(ITheServiceICareAbout);
}
public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
{
return IsAuthenticated
? FindHandlerForAuthenticatedUser(handlers)
: FindGuestHandler(handlers);
}
bool IsAuthenticated
{
get { return Thread.CurrentPrincipal != null; }
}
// ....
}
Only downside of handler selectors is that they're not pulled from the container - i.e. they're added as an instance to the container at registration time, so they don't get to have dependencies injected, lifestyle managed, etc., but there are ways to mitigate that - take a look at F.T.Windsor if you're interested in seeing how that can be done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With