Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dotnet core get a list of loaded assemblies for dependency injection

I'm using AutoFac to automatically register dependencies based on their interface implementations like so:

builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsImplementedInterfaces();

This works great for the entry assembly, but what about all of the related assemblies?

I'd like to do something like:

IList<Assembly> assemblies = GetLoadedAssemblies();
foreach(var assembly in assemblies)
{
  builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
}

I've searched and see a bunch of .netcore 1.0 stuff with AssemblyLoadContext, etc., but that no longer seems to exist in 1.1. Basically, when you search, you get lots of outdated references to stuff that no longer works.

There's got to be a way to get the currently loaded assemblies.

How can I do this?

like image 614
Robert Avatar asked Jun 22 '17 19:06

Robert


2 Answers

In .NET Core 2.0 Lots of APIs were brought from .NET Framework, among them is AppDomain.CurrentDomain.GetAssemblies() which allows you to get the assemblies that have been loaded into the execution context of application domain. Of course the concept wasn't fully ported from .NET Framework to .NET Core so you can't create your own app domains and treat them as unit of isolation inside single process (so you only have one app domain). But this is enough for what you want to achieve.

like image 59
Krzysztof Branicki Avatar answered Nov 08 '22 20:11

Krzysztof Branicki


You can use Scrutor which is working with .netstandard 1.6 or take a look how they're doing it here.

    public IImplementationTypeSelector FromAssemblyDependencies(Assembly assembly)
    {
        Preconditions.NotNull(assembly, nameof(assembly));

        var assemblies = new List<Assembly> { assembly };

        try
        {
            var dependencyNames = assembly.GetReferencedAssemblies();

            foreach (var dependencyName in dependencyNames)
            {
                try
                {
                    // Try to load the referenced assembly...
                    assemblies.Add(Assembly.Load(dependencyName));
                }
                catch
                {
                    // Failed to load assembly. Skip it.
                }
            }

            return InternalFromAssemblies(assemblies);
        }
        catch
        {
            return InternalFromAssemblies(assemblies);
        }
   }
like image 2
krlm Avatar answered Nov 08 '22 22:11

krlm