Get available types in CoreCLR

∥☆過路亽.° 提交于 2019-12-30 02:01:07

问题


This is easy to get all available types (for some interface for example) in the old .NET, but I can't find the way how to do that in the new CoreCLR.

What I want to do is to have function like GetRepository, that should look for existing implementation of IRepository and return new instance of that type. Implementation will be located in the different project.

So, in .NET I can use something like this:

AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())

The only solution I have for CoreCLR for now is:

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);
}

But it works only if interface and implementation are located in the same assembly (and this is not my case).

Thank you!


回答1:


So, here is the answer from Microsoft: https://github.com/dotnet/coreclr/issues/919

In short, there is new

Microsoft.Framework.Runtime.LibraryManager

with

public IEnumerable<ILibraryInformation> GetLibraries();
public IEnumerable<ILibraryInformation> GetReferencingLibraries(string name);

etc

UPD: starting from RC2 use Microsoft.Extensions.DependencyModel.DependencyContext instead:

DependencyContext.Default.CompileLibraries
DependencyContext.Default.RuntimeLibraries


来源:https://stackoverflow.com/questions/30007264/get-available-types-in-coreclr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!