查找通用接口的实现

时间:2018-12-31 15:56:26

标签: c# simple-injector system.reflection

我正在从程序集,一堆命令处理程序动态注册类:

class class DummyCommand : ICommand {}

class GetAgeCommandHandler : ICommandHandler<DummyCommand>
{
    public void Handle(DummyCommand command) { }
}

我有列出所有实现通用接口的类型的代码,在这种情况下,我对使用以下帮助程序方法的ICommandHandler<>接口感兴趣:

public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(this Assembly assembly, Type openGenericType)
{
    return from x in assembly.GetTypes()
            from z in x.GetInterfaces()
            let y = x.BaseType
            where
            (y != null && y.IsGenericType &&
            openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
            (z.IsGenericType &&
            openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
            select x;
}

具有以下注册代码:

var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var implementation in assembly.GetAllTypesImplementingOpenGenericType(typeof(ICommandHandler<>)))
{
    // below is wrong, i cannot get the generic type it is empty
    // var commandType = implementation.UnderlyingSystemType.GenericTypeArguments[0];
    // what should i put to find the type `DummyCommand`

    // registeration would be below
    var handlerType = (typeof(ICommandHandler<>)).MakeGenericType(commandType);
    container.Register(handlerType, implementation);
}

基本上,我正在尝试向SimpleInjector类型的container.Register(typeof(ICommandHandler<DummyCommand>), typeof(GetAgeCommandHandler))容器(但可以是任何ioc容器)进行注册,但在运行时具有泛型,所以我还需要谨慎处理类的情况实现多个ICommandHandler接口(不同命令类型)。

非常感谢指针。

1 个答案:

答案 0 :(得分:2)

您可能对阅读Simple Injector的fine manual on doing Auto-Registration感兴趣,因为可以将已发布代码的块简化为简单的单行代码:

container.Register(typeof(ICommandHandler<>), AppDomain.CurrentDomain.GetAssemblies());