Reputation: 20050
I'd like to intercept and inject custom code when calling 3rd party code in C#. I am using an external library (AutoIt) for GUI automation. The AutoIt dll is provided without source code.
All actions done with this framework are performed from a single class (AutoItClass
) providing access to all the methods. I'd like to be able to inject custom code when calling methods on this class, is this possible? For example:
This would be possible very simply by inheriting from this class and overriding all its methods (which is a must since this is a COM object), but this is not the preferred way. Any comments will be helpful!
Upvotes: 7
Views: 2478
Reputation: 8885
You can investigate PostSharp, which is a commercial product that can inject IL into compiled assemblies to perform aspect oriented programming. You can define different kind of behaviour that should happen before and after a method gets executed, for example, which seems to be what you want. This way, as PostSharp handles this in a post-compilation step, you don't need to create any inherited classes from the classes that you want to intercept.
Otherwise if you want a more "pure" solution I would follow Jon's advice about creating a new class that wraps the functionality of the one that you want to intercept. (see Decorator pattern) .
Upvotes: 3
Reputation: 1500675
I wouldn't use inheritance - you can use composition here. Create your own class which has the same methods - or in fact only the ones you're interested in - and delegate through that. That way you can be sure you won't "miss" any methods accidentally, because anything you don't implement won't be callable through the rest of your codebase... so long as you make sure the rest of your code doesn't refer to the original library class, of course.
Upvotes: 5