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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With