开发者

Castle windsor Adding conditional dependency

I have 2 implementations of开发者_Python百科 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.


One way to solve this would be, Register the service with key and then resolve as you need.

public interface ISample
{
    int Calculate(int a, int b);
}

class SampleB : ISample
{
    public int Calculate(int a, int b)
    {
        return a + b + 10;
    }
}

class SampleA : ISample
{
    public int Calculate(int a, int b)
    {
        return a + b;
    }
}

The registration:

        container.Register(Component.For<ISample>().ImplementedBy<SampleA>().Named("SampleA").LifeStyle.Transient);
        container.Register(Component.For<ISample>().ImplementedBy<SampleB>().Named("SampleB").LifeStyle.Transient);

// Resolve when SampleA needed.

var sampleA = container.Resolve<ISample>("SampleA");

// Resolve when SampleB needed.

var sampleB = container.Resolve<ISample>("SampleB");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜