问题
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