简体   繁体   中英

How to automatically Proxy a DLL(managed) through another DLL(managed)?

I have a strange request,

Actually our solution is this:

  • APP.EXE -> MYDLL.DLL

APP.EXE consumes MYDLL assembly methods.

Now the client request to implement this variations:

  • APP.EXE -> MYDLL_PROXY.DLL -> MYDLL.DLL (load dynamically)

MYDLL_PROXY.DLL must act like a proxy so, calling "MYDLL_PROXY.Method1" would load external MYDLL.DLL and invoke Method1 on it and return the result.

Something like this with reflection:

    //MYDLL_PROXY.dll
        ass = Assembly.LoadFrom(@"C:\mydll.dll");       
        String MyGenericMethod ="Something"
        Type MyType = ass.GetTypes()[0];
        Object o = Activator.CreateInstance(MyType);
        MethodInfo Method = ass.GetTypes()[0].GetMethod(MyGenericMethod);
        return Method.Invoke(null, new object[] { /* parameters go here */ });

So, before get mad, there is a quick'n'dirty way to create a fake dll that act like a proxy to another ?

I need to proxy all : Method, properties, events .

Thanks for any help.

NB : is an old project and must stay with Framework 2.0


Update

If reflections is not the correct way something like this incapsulate can be possible ? And what about the events ?

ExternalDLL:

public class NastyExternalClassInExternalDll
{
    public void Foo() { ... }
}

MainDLL:

public interface IFooable
{
    void Foo();
}

public sealed class NastyExternalClassWrapper : IFooable
{
    private readonly NastyExternalClassInExternalDll original;

    public NastyExternalClassWrapper(NastyExternalClass original)
    {
        this.original = original;
    }

    public void Foo()
    {
        original.Foo();
    }
}

One way is to use interfaces like you wrote in your question and wrap all methods\\properties. For events, you need to register to them in the proxy also and act.

Other way is to do it with rewriting concept. This can be made in two methods.

Statically: read the original dll (with cecil, dnlib etc) and for each method or property you encouraged, call your proxy code, then continue with the actual code. After all, that weaving, save the dll and you have done. The disadvantage of the static method is that for each change in the original dll, you need to run the wrapper again.

Dynamically: Attach a CLR Profiler to the original dll, and intercept all calls to your code before any method or property call.

I can't go further deeply here for each of these methods, because it will be long, but you can read on them and if you have a specific question, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM