c# - 温莎城堡 : Conditional registration of open generic types

标签 c# castle-windsor open-generics

我有以下内容:

class Repository<T> : IRepository<T>
interface ISuperRepository<T> : IRepository<T>
class SuperRepository<T> : ISuperRepository<T>
interface ISuperType

我想在 CaSTLe Windsor DI 中有条件地注册 IRepository<T> , 如果 TISuperType , 然后提供 ISuperRepository<T> .否则,提供 IRepository<T>.

例如,如果 A : ISuperType , 那么我要 Resolve<IRepository<A>>提供SuperRepository<A> , 和 Resolve<IRepository<B>>提供Repository<B> .

我怎样才能做到这一点?

最佳答案

CaSTLe Windsor 不支持这样的事情,但是你可以用一个简单的辅助方法来实现它:

public static void RegisterAccordingToISuperType<T>(this IWindsorContainer container)
{
    if (typeof (T).GetInterfaces().Contains(typeof (ISuperType)))
        container.Register(Component.For<IRepository<T>>()
                                    .ImplementedBy<SuperRepository<T>>());
    else
        container.Register(Component.For<IRepository<T>>()
                                    .ImplementedBy<Repository<T>>());
}

然后是注册:

container.RegisterAccordingToISuperType<SuperType>();
container.RegisterAccordingToISuperType<int>();

决心将:

var super = container.Resolve<IRepository<SuperType>>();
var intRepo = container.Resolve<IRepository<int>>();

另一个选项是 Component.For 中的额外参数。然后获取继承自 Type( For example ) 的所有类型并注册它们。

private static void Register(...)
{
    foreach (var type in GetInheriteTypes())
    {          
        container.Register(Component.For(typeof(IRepository<>),type)
                                    .ImplementedBy(typeof(SuperRepository<>)));
    }
    container.Register(Component.For(typeof(IRepository<>))
                                .ImplementedBy(typeof(Repository<>)));
}

private static IEnumerable<Type> GetInheriteTypes()
{
    var listOfBs = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                    from assemblyType in domainAssembly.GetTypes()
                    where assemblyType.GetInterfaces().Contains(typeof(ISuperType))
                    select assemblyType).ToArray();
    return listOfBs;
}

关于c# - 温莎城堡 : Conditional registration of open generic types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501966/

相关文章:

inversion-of-control - 通过参数名称解​​决 CasSTLe Windsor 依赖关系

wpf - 从 View 模型中单击按钮调用第二个 View

c# - 公开通用接口(interface)的非通用版本的模式

c# - Intellitrace 和 Windows 服务

c# - 当 EF 是另一个项目时,DropCreateDatabaseIfModelChanges

caSTLe-windsor - 温莎城堡 : UsingFactoryMethod can't instantiate with a weird error

c# - 如何使用 Autofac 注册开放通用接口(interface)的所有实现

ninject - 如何使用 Ninject 约定扩展将泛型类型与继承绑定(bind)

c# - 我真的要返回最短日期吗?

c# - OnClientClick 不适用于 asp.net LinkBut​​ton