获取CoreCLR中的可用类型

Dmi*_*sky 12 c# coreclr dnx

这很容易获得旧.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)

但它只有在接口和实现位于同一个程序集中时才有效(这不是我的情况).

谢谢!

Dmi*_*sky 9

所以,这是微软的答案:https: //github.com/dotnet/coreclr/issues/919

总之,有新的

Microsoft.Framework.Runtime.LibraryManager
Run Code Online (Sandbox Code Playgroud)

public IEnumerable<ILibraryInformation> GetLibraries();
public IEnumerable<ILibraryInformation> GetReferencingLibraries(string name);
Run Code Online (Sandbox Code Playgroud)

等等

UPD:从RC2开始使用Microsoft.Extensions.DependencyModel.DependencyContext:

DependencyContext.Default.CompileLibraries
DependencyContext.Default.RuntimeLibraries
Run Code Online (Sandbox Code Playgroud)