Change access modifier for access with reflection

I have a scenario where I am using a dynamic padlock proxy to be able to intercept and log message calls to any class (let's call it the target class). I do this by wrapping the target class in a class that creates a class proxy with an interceptor that logs all method calls to the target class. This works great. The only problem is that it requires all public methods in the target class to be virtual, which is otherwise undesirable.

I could create a solution where I check that all methods are virtual when I create a proxy and throws an exception if they are not, but I would prefer if it was possible to change the methods to be virtual using reflection (or whatever) before creating the proxy. This way I can use it on all classes, regardless of whether it has virtual methods or not.

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

+3


source to share


2 answers


You cannot change whether a method is virtual or not using reflection. In fact, you cannot change anything at all with reflection, it is a read-only interface to your type structure (as it should be).



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

+4


source


You can do this with Mono Cecil .



This method is really the only option unless you have control over the code used to build the assembly.

+1


source







All Articles