Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a class implementing an interface dynamically

I'm trying to write a code that allows a user to load an assembly (DLL file), choose an interface in said assembly, than generates a class inheriting that interface, with stubs for all required methods.

The class would be generated either into a file or into an active VS session (the code is intended for use inside an IWizard initialized during project creation through a custom template).

I got to the point where I have the Type object of the interface, but I'm having a hard time figuring the next part, I've contemplated running across the interface's methods in a loop and copying them into a textual file, adding the stub implementations in the appropriate places but I'm pretty sure there's some better method, perhaps through a third party tool?

Any help would be appreciated, Thank you in advance.

like image 972
JohnoBoy Avatar asked Oct 15 '22 01:10

JohnoBoy


1 Answers

If you want to create a new type at runtime, you'll need to use Reflection.Emit. Reflection.Emit allows you to emit Intermediate Language directly into the current AppDomain (or an assembly if you prefer.) You probably want to use the type in memory, so you may not want to create an actual assembly.

Creating new type is done with the TypeBuilder class.

Codeproject has an excellent introduction: http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

UPDATE:

It has been brought to my attention that the goal is to add a C# code file to an existing project. You would still need to reflect into the assembly and emit IL, but then you'd have to "dissasemble" the IL into C#. Reflector is the #1 recommended tool for this, though I'm not sure it can be automated in the way you want.

like image 58
Dave Swersky Avatar answered Oct 20 '22 16:10

Dave Swersky