Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get available types in CoreCLR

Tags:

c#

coreclr

dnx

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!

like image 880
Dmitry Sikorsky Avatar asked May 02 '15 20:05

Dmitry Sikorsky


1 Answers

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
like image 155
Dmitry Sikorsky Avatar answered Oct 26 '22 14:10

Dmitry Sikorsky