Skip to content

Instantly share code, notes, and snippets.

@redknightlois
Created September 1, 2014 17:42
Show Gist options
  • Save redknightlois/a9ac805fec178402fa00 to your computer and use it in GitHub Desktop.
Save redknightlois/a9ac805fec178402fa00 to your computer and use it in GitHub Desktop.
Roslyn compile source without writing to disk on the same AppDomain.
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace RoslynNuget
{
public interface IRunnableFromLoadedAssembly
{
void Run();
}
public class LoadAssemblyProgram
{
static void Main(string[] args)
{
var assembly = Compile(@"
using System;
using System.IO;
using RoslynNuget;
public class MyType : IRunnableFromLoadedAssembly
{
public void Run ()
{
Console.WriteLine (""It's alive."");
}
}
");
var type = assembly.GetType("MyType");
var obj = (IRunnableFromLoadedAssembly) Activator.CreateInstance(type);
obj.Run();
Console.ReadLine();
}
public static Assembly Compile(params string[] sources)
{
var assemblyFileName = "gen" + Guid.NewGuid().ToString().Replace("-", "") + ".dll";
var compilation = CSharpCompilation.Create(assemblyFileName,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: from source in sources
select CSharpSyntaxTree.ParseText(source),
references: new[]
{
new MetadataFileReference(typeof(object).Assembly.Location),
new MetadataFileReference(typeof(RuntimeBinderException).Assembly.Location),
new MetadataFileReference(typeof(DynamicAttribute).Assembly.Location),
new MetadataFileReference(typeof(LoadAssemblyProgram).Assembly.Location)
});
EmitResult emitResult;
using (var ms = new MemoryStream())
{
emitResult = compilation.Emit(ms);
if (emitResult.Success)
{
var assembly = Assembly.Load(ms.GetBuffer());
return assembly;
}
}
var message = string.Join("\r\n", emitResult.Diagnostics);
throw new Exception(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment