Dynamically creating an assembly targeting a specific .NET runtime using Reflection.Emit

548 views Asked by At

I'm using Reflection.Emit to develop a tool that dynamically creates an Assembly at runtime.

The tool is targeting the .NET 4.5 framework.

I'd like to know if it's possible to specify which .NET runtime the dynamically generated assembly targets (e.g: specify that a .NET 3.5 assembly will be created, for example).

1

There are 1 answers

9
Marc Gravell On

The inbuilt reflection-emit is pretty limited here; what you want to do is tell it to use a specific mscorlib assembly, but the problem is that a lot of reflection-emit involves passing Types around, which makes this incredibly hard. The most pragmatic way I found to approach this problem was to switch to IKVM.Reflection.dll - part of IKVM.NET. This dll has very deliberately the same basic API as Reflection.Emit, but instead of operating against the inbuilt Type objects, it operates against the IKVM instances, which are loaded in the concept of a Universe. A Universe can then load the desired mscorlib dll, and whichever other dlls you require.

The changes for this is usually just changing the using statements. This approach is used throughout protobuf-net (in particular the precompile tool), allowing not just different versions, but entire different frameworks to be targeted. Want to create a dll that targets silverlight from a regular .NET application? Not a problem. The trickiest bit (IMO) becomes simply finding the correct mscorlib and supporting files to load into the Universe.

See my blog post Enter the IKVM - or see the examples on IKVM, like Function Pointer Types.

I can provide more info as required.