nuno.filipesf
nuno.filipesf

Reputation: 775

Resolve dependencies when loading an assembly in .NET Core

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 thought 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 .NET Core?

Upvotes: 6

Views: 4874

Answers (1)

antonpv
antonpv

Reputation: 937

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.

Upvotes: 5

Related Questions