将IRepo <t>注册到2个实现,以便根据T(T实现的接口)解析它</t>

时间:2011-04-01 12:00:16

标签: c# .net castle-windsor ioc-container factory

我有这样的事情:

public class IRepo<T>
{
}

public class EntRepo<T> : IRepo<T> where T : Entity
{
}

public classs DelRepo<T> : IRepo<T> where T : Entity, IDel
{
}

我将如何注册这一点,以便当我Resolve实施IDel的T实现时,我会得到DelRepo,在休息时我会得到EntRepo

2 个答案:

答案 0 :(得分:2)

使用IHandlerSelector ........

答案 1 :(得分:1)

您可以编写一个装饰器/路由器,它知道要路由的两个实现。这是一个例子:

public class RepoRouter<T> : IRepo<T> where T : Entity
{
    private static readonly bool isDelType;
    private readonly IWindsorContainer container;

    static RepoRouter()
    {
        isDelType = typeof(IDel).IsAssignableFrom(typeof(T));
    }

    public RepoRouter(IWindsorContainer container)
    {
        this.container = container;
    }

    // Implement all interface members of IRepo<T> here.
    void IRepo<T>.MyInterfaceMethod(T value)
    {
        this.GetRepo().MyInterfaceMethod(value);
    }

    private IRepo<T> GetRepo()
    {
        return isDelType ?
            this.container.Resolve<DelRepo<T>>() :
            this.container.Resolve<EntRepo<T>>();
    }
}

您现在可以在容器中注册此RepoRouter<T>