Is there an alternative for BuildManager.GetReferencedAssemblies() in ASP.NET Core?

Viewed 1548

In ASP.NET MVC 5 I used the BuildManager.GetReferencedAssemblies() method to get all the assemblies in the bin folder and load them before the dependency started, so all the dlls were available to be scanned and injected.

Is there an alternative in ASP.NET Core?

https://docs.microsoft.com/en-us/dotnet/api/system.web.compilation.buildmanager.getreferencedassemblies?view=netframework-4.7.2

I tried this code but it started do give me load errors, like file not found exceptions.

foreach (var compilationLibrary in deps.CompileLibraries)
{
    foreach (var resolveReferencePath in compilationLibrary.ResolveReferencePaths())
    {
        Console.WriteLine($"\t\tReference path: {resolveReferencePath}");
        dlls.Add(resolveReferencePath);
    }
}
dlls = dlls.Distinct().ToList();
var infolder = dlls.Where(x => x.Contains(Directory.GetCurrentDirectory())).ToList();
foreach (var item in infolder)
{
    try
    {
        Assembly.LoadFile(item);
    }
    catch (System.IO.FileLoadException loadEx)
    {

    } // The Assembly has already been loaded.
    catch (BadImageFormatException imgEx)
    {

    } // If a BadImageFormatException exception is thrown, the file is not an assembly.
    catch (Exception ex)
    {

    }
}
1 Answers

I managed to create a solution, but i'm not sure it solves all cases.

I'll post as "Works on my machine solution"

The majos difference is the change from Assembly.LoadFile to AssemblyLoadContext.Default.LoadFromAssemblyPath

I used this texts as research

https://natemcmaster.com/blog/2018/07/25/netcore-plugins/ https://github.com/dotnet/coreclr/blob/v2.1.0/Documentation/design-docs/assemblyloadcontext.md

        var dlls = DependencyContext.Default.CompileLibraries
            .SelectMany(x => x.ResolveReferencePaths())
            .Distinct()
            .Where(x => x.Contains(Directory.GetCurrentDirectory()))
            .ToList();
        foreach (var item in dlls)
        {
            try
            {
                AssemblyLoadContext.Default.LoadFromAssemblyPath(item);
            }
            catch (System.IO.FileLoadException loadEx)
            {
            } // The Assembly has already been loaded.
            catch (BadImageFormatException imgEx)
            {
            } // If a BadImageFormatException exception is thrown, the file is not an assembly.
            catch (Exception ex)
            {
            }
        }
Related