9

I want to add some behavior to a certain class at runtime. I know how to subclass at runtime using Reflection.Emit but that's not enough. Depending on some external configuration I need to inject opcodes in a method on a type T so all classes that inherit from it automatically gain this behavior. (I can't use the .NET Profiling API).

Can something like this be done with Mono.Cecil?

If it isn't possible to modify code on a loaded assembly, it is fine If I can make the modifications before the assembly is loaded and then load the modified assembly in memory, but I don't know how I can control assembly loading.

bad_coder
  • 5,829
  • 13
  • 26
  • 41
Thiago de Arruda
  • 4,360
  • 5
  • 37
  • 66
  • Are you asking because you want to optimize the code? Are you open to the idea of sampling as an alternative to instrumentation? Many people believe in instrumentation because it's "accurate", which is not what you need for optimization. If you want to optimize, consider this method: http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024 – Mike Dunlavey May 03 '10 at 11:32
  • Its not optimization I'm looking for, what I want is to add some behavior to a framework based on configuration. For example, take the TypeDescriptor inspection mechanism, if I read some configuration and add some public property to a base class T, then whoever inspects T or any of its subclasses using the TypeDescriptor mechanism will see the property, but if the same inspection is made using reflection the property will be missing. Thats because the Type is not actually modified, the property is just added in the context of the TypeDescriptor inspection. – Thiago de Arruda May 03 '10 at 19:57

2 Answers2

6

Nope, Cecil can not modify a loaded assembly. You have to instrument assemblies before they are actually loaded.

You don't have much control over how assemblies are resolved. You can hook into AppDomain.AssemblyResolve if you hide the assemblies in a private folder of yours, and instrument then before loading them.

Jb Evain
  • 16,611
  • 2
  • 63
  • 66
1

As JB Says above- You can create a Resolve Event handler - which would be like PSeudoHooking. And before the assembly is loaded, you make your changes, and then once the changes are done, the Resolve Assembly then continues on to load the changed assembly.

I use this method for resolving Embedded Dll's from Memory Streams.