这很容易获得旧.NET中的所有可用类型(例如某些接口),但我无法在新的CoreCLR中找到如何做到这一点的方法.
我想要做的是拥有像GetRepository这样的函数,它应该查找IRepository的现有实现并返回该类型的新实例.实施将位于不同的项目中.
所以,在.NET中我可以使用这样的东西:
AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
Run Code Online (Sandbox Code Playgroud)
我现在对CoreCLR唯一的解决方案是:
public T GetRepository<T>()
{
foreach (Type type in typeof(T).GetTypeInfo().Assembly.GetTypes())
if (typeof(T).IsAssignableFrom(type) && type.GetTypeInfo().IsClass)
return (T)Activator.CreateInstance(type);
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
但它只有在接口和实现位于同一个程序集中时才有效(这不是我的情况).
谢谢!