Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for AppDomain.GetLoadedAssemblies() in .NET Core?

I'm trying to write some logic to mirror some existing logic in an original .NET application. In my OnModelCreating() method I want to load all current types in loaded assemblies to find the ones that need to be registered for entity type configuration in the model.

This was done in .NET with AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetTypes()), however AppDomain no longer exists in .NET Core.

Is there a new way to do this?

I have seen some examples online of using DependencyContext.Default.RuntimeLibraries however DependencyContext.Default does not seem to exist anymore either.

Edit:

I have found now that adding Microsoft.Extensions.DependencyModel to a .netcoreapp1.1 project works. However I am actually writing a solution with multiple projects and I somehow need do this type loading in my .netstandard1.4 project where my DbContext implementation and entity type configuration is

like image 347
mbrookson Avatar asked May 14 '17 15:05

mbrookson


People also ask

What is AppDomain in .NET Core?

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown. For more information on using application domains, see Application Domains.

Does .NET Core support remoting?

NET Remoting isn't supported on . NET 5+ (and . NET Core). . NET remoting was identified as a problematic architecture.


1 Answers

What you are looking for is broadly explained here. The author recommends creating a polyfill.

I am going to copy and paste in case the page goes missing.

public class AppDomain
{
    public static AppDomain CurrentDomain { get; private set; }

    static AppDomain()
    {
        CurrentDomain = new AppDomain();
    }

    public Assembly[] GetAssemblies()
    {
        var assemblies = new List<Assembly>();
        var dependencies = DependencyContext.Default.RuntimeLibraries;
        foreach (var library in dependencies)
        {
            if (IsCandidateCompilationLibrary(library))
            {
                var assembly = Assembly.Load(new AssemblyName(library.Name));
                assemblies.Add(assembly);
            }
        }
        return assemblies.ToArray();
    }

    private static bool IsCandidateCompilationLibrary(RuntimeLibrary compilationLibrary)
    {
        return compilationLibrary.Name == ("Specify")
            || compilationLibrary.Dependencies.Any(d => d.Name.StartsWith("Specify"));
    }
}
like image 50
MaLiN2223 Avatar answered Sep 27 '22 18:09

MaLiN2223