I’m generating a Greeter.dll using the Roslyn compiler. My problem occurs trying to load the DLL file.
Here’s the code:
using System;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
using System.IO;
using System.Reflection;
using System.Linq;
namespace LoadingAClass
{
class Program
{
static void Main(string[] args)
{
var syntaxTree = SyntaxTree.ParseCompilationUnit(@"
class Greeter
{
static void Greet()
{
Console.WriteLine(""Hello, World"");
}
}");
var compilation = Compilation.Create("Greeter.dll",
syntaxTrees: new[] { syntaxTree },
references: new[] {
new AssemblyFileReference(typeof(object).Assembly.Location),
new AssemblyFileReference(typeof(Enumerable).Assembly.Location),
});
Assembly assembly;
using (var file = new FileStream("Greeter.dll", FileMode.Create))
{
EmitResult result = compilation.Emit(file);
}
assembly = Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), @"Greeter.dll"));
Type type = assembly.GetType("Greeter");
var obj = Activator.CreateInstance(type);
type.InvokeMember("Greet",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
Console.WriteLine("<ENTER> to continue");
Console.ReadLine();
}
}
// Thanks, http://blogs.msdn.com/b/csharpfaq/archive/2011/11/23/using-the-roslyn-symbol-api.aspx
}
The error message occurs on the line assembly = Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), @"Greeter.dll")); and reads
Im Modul wurde ein Assemblymanifest erwartet. (Ausnahme von HRESULT: 0x80131018)
Which roughly translates to
An assembly manifest was expected in the module.
Does anyone know what I’m missing here?
I have been adding Roslyn support to the O2 Plarform and here is how you can use its Roslyn support to compile (code), create (and assembly) and invoke (its method) one line of code:
Here is a version that executes a code snippet that looks like yours (I added a return value):
For a couple more details and screenshots of what this looks like, see this blog post: 1 line to compile, create and execute: O2 Script to use Roslyn to Dynamically compile and execute a method
UPDATE: see http://blog.diniscruz.com/search/label/Roslyn for a large number number of Roslyn related posts and tools (created using the O2 Platform)