Search code examples
c#.netreflectionmethodstypedescriptor

Programmatically add methods to class?


I'm dealing with an API, that has a class of million methods, I know what these methods do, they're just proxies to a web-service.

The API internally calls these proxy methods using reflection invoking the appropriate method name (don't ask me why it's done this way).

There are methods in the web-services not implemented by the API, and I need to 'inject' these proxy methods dynamically.

So my question is: How can I add methods to an existing class (not extension methods)?

I could do this by Reflection.Emit, but I don't know MSIL.
Anyway I'm mentioning it, because I've made another class that inherits from the same base class as the API does, and implemented the methods there, so maybe there is a way to copy the methods to the API class, because they only call methods of the base class which refers to the same one.


Solution

  • Realistically, there's no way you're going to modify an existing class in the way you want. Even using Reflection.Emit, it won't do what you want because the API is calling a specific type, and you can't modify the definition of a type during runtime. What you can do with Reflection.Emit is define a type that inherits from the proxy, but getting the API to load your inherited type will probably prove to be impossible unless they're using a dependency injection framework, which seems unlikely.

    The only real way to do this is to go in and modify the bytecode of the dll using decompilation and recompilation. This is how Postsharp does AOP, but imo, I'd never do this for any other reason.

    If you have any access to this code or even their libraries, then there is probably a better way around your problem.