3

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?

iCediCe
  • 1,672
  • 1
  • 15
  • 32

2 Answers2

4

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.

Erik
  • 5,355
  • 25
  • 39
  • Ah! This is a great answer. But I made my wrapper so in can either just log the calls or it can log the calls and the by invoking invocation.proceed() make the actual call, will this be possible with this approach? – iCediCe Jul 23 '15 at 16:11
  • Yeah, as I understand it, that should work fine with this approach. – Erik Jul 23 '15 at 16:12
  • Awsome. This will be the solution the. thank you for the fast answer! – iCediCe Jul 23 '15 at 16:16
1

You can do this with Mono Cecil.

This method is really the only option if you don't control the code used to produce the assembly.

Elan Hasson
  • 1,214
  • 1
  • 19
  • 29
  • I went for the interface solution, but this is interesting. This will probably come in handy at some point. Thanks. – iCediCe Jul 27 '15 at 08:37
  • 1
    would be nice if you wrote a small example, not link-only too. thanks anyway – T.Todua May 25 '19 at 08:29