How to compile in memory and get assembly using Microsoft.CodeAnalysis

1k Views Asked by At

Before I was using System.CodeDom.Compiler. It has options that allow compiling in memory and return assembly:

var compilerParams = new CompilerParameters
        {
            GenerateInMemory = true,
            GenerateExecutable = false,
        };

I am migrating to .net core and I am using Microsoft.CodeAnalysis to compile from the string. But I couldn't find 'compile in memory' function on it. My goal is to validate the syntax issue of code. Currently my code is:

 var sources = GenerateSourceFromDefaultValue(context, defaultValue, clrType, isEnum);
        var parsedSyntaxTree = Parse(sources, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
        var compilation = CSharpCompilation.Create("Test.dll", new SyntaxTree[] { parsedSyntaxTree }, options: DefaultCompilationOptions);
1

There are 1 best solutions below

0
On BEST ANSWER

The following code worked on me

 Assembly assembly = null;
        using (var memoryStream = new MemoryStream())
        {
            var emitResult = compilation.Emit(memoryStream);
            if (emitResult.Success)
            {
                memoryStream.Seek(0, SeekOrigin.Begin);

                var assemblyLoadContext = AssemblyLoadContext.Default;

                assembly = assemblyLoadContext.Assemblies.FirstOrDefault(a => a.GetName()?.Name == AssemblyName);
                if (assembly == null)
                {
                    assembly = assemblyLoadContext.LoadFromStream(memoryStream);
                }
            }
        }

        return assembly;