Modifying a type at runtime

  • Thread starter Thread starter Richard Dutton
  • Start date Start date
R

Richard Dutton

I would like to be able to modify a type at runtime so that I can add an IL
prologue and epilogue to its methods (either to implement some kind of
aspect-oriented programming framework, or a simple profiling tool). I know
that a simlpe way to achieve the same behaviour, at least for a type's
virtual methods, is to derive a new type and add my code before and after
calls to the inner object's methods, but for my own edification I'd like to
try to actually inject the code into the existing type.

TypeBuilder, MethodRental and their cohorts in Reflection.Emit look like
they are capable of performing such injection, but only on types in a
dynamic assembly so my questions are these:
Is it at all possible to use Reflection.Emit.*Builder on types in an
assembly that has been loaded from disc (and acquired using
Assembly.GetExecutingAssembly, for example).
If not, is it possible somehow to copy an Assembly into an AssemblyBuilder
(or Module into ModuleBuilder and so on) in order to modify that.
Is there another dynamic way to perform the injection (i.e. not using
il(d)asm).

Many thanks,

Richard Dutton
 
Richard,

It is not possible to inject code into an assembly that is already
loaded. You will have to create a new, dynamic assembly in another app
domain (as you already know).

There is no way to say "base the new assembly on this one", from what I
can tell about defining a dynamic assembly.

Check out the article in MSDN magazine by Dharma Shukla, Simon Fell, and
Chris Sells titled "Aspect-Oriented Programming Enables Better Code
Encapsulation and Reuse" located at (watch for line wrap):

http://msdn.microsoft.com/msdnmag/issues/02/03/AOP/

Also, you might be able to simulate aspect oriented programming by using
some of the profiling interfaces for the CLR (which have hooks for when IL
is compiled into native code), but it is a messy affair.

Honestly, I think it might be much, much easier to do what you want
using attributes and defining some limitations on your components which
would help set up context for the attributes (for example, you must use a
class factory so that you can set a context of some kind on creation, etc,
etc)

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top