[英]Find implementation of generic interface
我正在從程序集,一堆命令處理程序動態注冊類:
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
容器(但可以是任何ioc容器)注冊類型為container.Register(typeof(ICommandHandler<DummyCommand>), typeof(GetAgeCommandHandler))
但要在運行時使用泛型,我還需要注意處理一個類實現多個ICommandHandler
接口(不同命令類型)的情況。
指針非常感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.