How to load assemblies in ASP.NET Core 1.0 RC2

porting my web application from ASP.NET Core RC1 to RC2. I am trying to load my referenced class libraries.

This piece of code no longer works with RC2.

public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // libraryManager is null .... ILibraryManager libraryManager = app.GetService<ILibraryManager>(); List<Assembly> result = new List<Assembly>(); IEnumerable<Library> libraries = libraryManager.GetLibraries(); IEnumerable<AssemblyName> assemblyNames = libraries.SelectMany(e => e.Assemblies).Distinct(); assemblyNames = Enumerable.Where(assemblyNames, e => e.Name.StartsWith("projectNamespace")); foreach (AssemblyName assemblyName in assemblyNames) { Assembly assembly = Assembly.Load(assemblyName); . . . } } } 

Our help would be greatly appreciated, thanks Stefan

+7
coreclr
source share
2 answers

I have found a solution. I am now using DependencyContext instead of ILibraryManager

 var loadableAssemblies = new List<Assembly>(); var deps = DependencyContext.Default; foreach (var compilationLibrary in deps.CompileLibraries) { if (compilationLibrary.Name.Contains(projectNamespace)) { var assembly = Assembly.Load(new AssemblyName(compilationLibrary.Name)); loadableAssemblies.Add(assembly); } } 
+12
source share

I think Steve made 2 wrong assumptions:

1) that the project namespace must be part of the name of the compilation library.
2) that the name of the compilation library matches the name of the binary file.

At first you are mistaken when you change it in the project settings. The second one is incorrect if you specify it in buildOptions in project.json.

So your idea is correct, but the implementation is wrong. To fix this, we need to forget about resolving the namespace before loading the assembly.
I think since all assemblies will be loaded anyway, we won’t get a big performance delay.

But this is not a panacea ... an assembly can have multiple root namespaces inside! Therefore, it is best to define an attribute at the assembly level and test it instead of the namespace.

In any case, if you want to limit the search by assembly name, this should be done as follows:

 IEnumerable<AssemblyName> names = DependencyContext.Default.GetDefaultAssemblyNames(); foreach (AssemblyName name in names) { if (name.Name.StartsWith("MyRoot") == true) { Assembly assembly = Assembly.Load(name); // Process assembly here... // I will check attribute for each loaded assembly found in MyRoot. } } 
+4
source share

All Articles