Created
January 3, 2021 06:09
-
-
Save conikeec/6e13e0d558cc244689a44c9a4f0ff938 to your computer and use it in GitHub Desktop.
Roslyn based metaprogram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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