How to intercept method calls in C #

I would like to intercept and enter my own code when calling third-party code in C #. I use an external library (AutoIt) to automate the graphical interface. The AutoIt dialog box is provided without source code.

All actions performed in this structure are performed from one class ( AutoItClass ), which provides access to all methods. I would like to be able to enter custom code when calling methods in this class, is this possible? For instance:

  • Record some information from the called method.
  • Perform any other action from the method (wait X seconds).

This would be possible very simply, inheriting from this class and overriding all its methods (which is mandatory, since it is a COM object), but this is not the most preferred way. Any comments would be helpful!

+6
c # autoit
source share
2 answers

I would not use inheritance - here you can use composition. Create your own class that has the same methods - or actually only those that interest you - and delegate this through. Thus, you can be sure that you will not “skip” any methods by accident, because everything that you do not implement will not be called through the rest of your code base ... until you make sure that the rest of your code does not work Of course, refer to the source class of the library.

+4
source share

You can explore PostSharp , which is a commercial product that can inject IL into compiled assemblies to perform aspect-oriented programming . You can define different types of behavior that must occur before and after the method is executed, for example, which seems to be what you want. Thus, since PostSharp handles this after compilation, you do not need to create any inherited classes from the classes you want to intercept.

Otherwise, if you want a cleaner solution, I will follow John’s advice on creating a new class that wraps the functions of what you want to intercept. (see Figure decorator ).

+3
source share

All Articles