Created
December 28, 2012 07:44
-
-
Save joeriks/4395547 to your computer and use it in GitHub Desktop.
Add a piece of dynamically compiled code in memory with the help of Roslyn. (After this the Greeter class will be available and can be run from example from the immediate window in visual studio).
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 void AddGreeter() | |
{ | |
AddInmemory("Greeter", @"using System; | |
class Greeter | |
{ | |
public string Greet() | |
{ | |
return ""Hello World""; | |
} | |
}"); | |
} | |
public static void AddInmemory(string inMemoryAssemblyName, string code ) | |
{ | |
var syntaxTree = SyntaxTree.ParseText(code); | |
var refs = new[] { | |
MetadataReference.CreateAssemblyReference("mscorlib"), | |
}; | |
var compilation = Compilation.Create(inMemoryAssemblyName, | |
syntaxTrees: new[] { syntaxTree }, | |
references: refs, | |
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary)); | |
using (var memoryStream = new MemoryStream()) | |
{ | |
EmitResult result = compilation.Emit(memoryStream); | |
memoryStream.Flush(); | |
var assembly = Assembly.Load(memoryStream.GetBuffer()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment