Search code examples
c#.netreflectioncastle-dynamicproxy

Changing method access modifier with reflection


I have a scenario where I use castle dynamic proxy to be able to intercept and log message calls to any given class(let's call it the target class). I do this by wrapping the target-class in a class that creates a proxy of the class with a interceptor that logs all method calls to the target-class. This works fine. The only issue is that for this to work all public methods on the target-class needs to be virtual which for more reasons is not desirable.

I could create a solution where i validate that all methods are virtual when I create the proxy and throws a exception if this is not the case, but I would rather if it was possible to change the methods to be virtual using reflection (or something else) before generating the proxy. This way I will be able to use the on all classes without paying attention to if it has virtual methods or not.

What am I missing here, can I archive this somehow?


Solution

  • You can't alter whether a method is virtual or not by using reflection. Actually, you can't alter anything at all with reflection, it's a read-only interface to your type structure (as it should be).

    Your best option is to create an interface for the class, update references to it to use the interface and build the proxy off the interface. Then your class doesn't have to have virtual methods but your proxy will implement the interface and the interceptor will work.