In ordinary native libraries, I can wrap another dll and monitor calls by simply building a dll with the same exact function signatures in the export, and sometimes can even call onto the real dll.
In managed C#, I have a dll called "A" that is a plugin for another application that has a class that derives from a class in another dll I called dll "B". I want to make a wrapper dll for "B", so "A" can function with a wrapped version of "B", and might not even use the real version of "B" at all.
B also has static methods and other classes, I want to be able to redefine the signatures/declarations in this quasi-wrapper and have the "A" assembly use that instead.
Plugin dll A:
using baseD开发者_如何学编程llB;
public class foopluginA : pluginclassB
{
public void methodbaz() { base.doStuff(); pluginclassB.doStaticStuff(); }
}
Base dll B:
namespace baseDllB
{
public class pluginclassB
{
public void doStuff()
{
//Do stuff
}
public static void doStaticStuff() { /*Do more stuff*/ }
}
}
The plugin dll
s reference B obviously, so what I want to do is recreate B
where I'm able to perform logging, etc.
What ways are there to do this?
You can certainly write an assembly which had a class that forwarded all of its method calls and internal state to other classes. However, there are a few difficulties you'd have to overcome.
You would have to replace references to the original assembly with your new wrapper assembly.
You would have to reflect class changes in the wrapper to the wrapped class. This can be non-trivial, especially if the internal state contains private members. If it's a static class, that's a lot easier.
If you wanted your wrapper assembly to be able to load more than one kind of wrapped assembly, for example to choose which class to forward to, you would either need to write an interface and make the wrapped assemblies derive from that interface, or your code in your wrapper assembly would become very complex.
If you wanted your wrapper assembly to be totally dynamic, meaning it loaded its wrapped target at runtime and only the one you wanted, you'd need to make heavy use of reflection to get methods and other items from the wrapped class.
One possibility is RealProxy
. You can use the RealProxy
class to provide proxy instances of other classes, and the client code won't know the difference. Here is a blog post with an example of its usage.
精彩评论