Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve dependecies when loading an assembly in .Net Core

Tags:

I have a project in .net Core and I need to load an Assembly (compiled with Roslyn) to a sandbox, in order to isolate the code execution.

My first tought was use an AppDomain, but it's not possible in .net Core. So, the solution is to use AssemblyLoadContext.

The following code is my Assembly Loader:

public class AssemblyContext : AssemblyLoadContext
{
    public Assembly Load(Stream stream)
    {
        this.Resolving += ResolvingHandler;
        return this.LoadFromStream(stream);
    }

    public Assembly ResolvingHandler(AssemblyLoadContext context, AssemblyName assemblyName)
    {
        var assembly = context.LoadFromAssemblyName(assemblyName);
        Console.WriteLine("Resolving: " + assemblyName.FullName);
        return assembly;
    }
}

My problem here is after the load of the Assembly, the Resolving method is not called and the dependencies are not loaded, making my compiled code not working.

Is necessary to do any additional steps to the ResolvingHandler be called? Or this isn't possible to do in Core?

like image 446
nuno.filipesf Avatar asked Nov 14 '17 09:11

nuno.filipesf


1 Answers

As from documentation it is not called by design:

AssemblyLoadContext.Resolving Event

Occurs when the resolution of an assembly fails when attempting to load into this assembly load context.

like image 100
antonpv Avatar answered Sep 20 '22 13:09

antonpv