How to wrap assemblies in .NET?

会有一股神秘感。 提交于 2019-12-24 01:54:09

问题


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 baseDllB;
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 dlls 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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6933581/how-to-wrap-assemblies-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!