Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle windsor Adding conditional dependency

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?

like image 539
Mark Avatar asked Sep 21 '11 15:09

Mark


1 Answers

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.

like image 80
mookid8000 Avatar answered Sep 21 '22 03:09

mookid8000