Skip to content

Instantly share code, notes, and snippets.

@conikeec
Created Jan 3, 2021
Embed
What would you like to do?
Roslyn based metaprogram
public static Assembly Compile(string[] sources, bool isDebug, string tempDir, params AssemblyName[] referencedAssemblies)
{
var assemblyFileName = tempDir + "gen" + Guid.NewGuid().ToString().Replace("-", "") + ".dll";
var assemblyPath = Path.GetFullPath(assemblyFileName);
var compilation = Compilation.Create(assemblyFileName,
new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddSyntaxTrees(from source in sources
select SyntaxTree.ParseCompilationUnit(source))
.AddReferences(from ass in referencedAssemblies
select new AssemblyFileReference(new Uri(ass.CodeBase).LocalPath))
select new AssemblyObjectReference(Assembly.Load(ass)))
.AddReferences(from ass in new[]
{
"System",
"System.Core",
"mscorlib"
}
select new AssemblyNameReference(ass));
EmitResult emitResult;
using (var stream = new MemoryStream())
using (var stream = new FileStream(assemblyPath, FileMode.Create, FileAccess.Write))
{
emitResult = compilation.Emit(stream);
}
if (!emitResult.Success)
{
var message = string.Join("\r\n", emitResult.Diagnostics);
throw new ApplicationException(message);
}
return Assembly.LoadFile(assemblyPath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment