Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load assembly from stream in .NET Core

Tags:

c#

.net

.net-core

I am experiencing with Roslyn on a .NET Core console application. I tried to create an assembly and compile it into a memory stream. But loading it seems to be missing an API (that normally works on the regular .NET Framework)

var compilation = CSharpCompilation.Create("MyCompilation",
         syntaxTrees: new[] { pocoTree }, references: new[] { mscorlib, currentAssembly });

var ms = new MemoryStream();
var emitResult = compilation.Emit(ms);

var ourAssembly = Assembly.Load(ms.ToArray()); // Fails to compile here

I get this error:

cannot convert from 'byte[]' to 'System.Reflection.AssemblyName'

What is the alternative in .NET Core to load from a steam? (other than physically saving the assembly and loading it)

like image 822
Moslem Ben Dhaou Avatar asked Dec 14 '22 02:12

Moslem Ben Dhaou


1 Answers

You can load the assembly from a stream in .NET core using AssemblyLoadContext:

// requires "System.Runtime.Loader": "4.0.0",
protected virtual Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)
{
    return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(peStream, pdbStream);
}
like image 179
meziantou Avatar answered Dec 24 '22 22:12

meziantou