Load different version of assembly into separate AppDomain

前端 未结 2 1558
失恋的感觉
失恋的感觉 2020-12-10 09:08

I\'m implementing application that supports plugins. Currently the problem arises when I try to load common assembly that is used both by host application and plugi

相关标签:
2条回答
  • 2020-12-10 09:49

    Most likely it is your own code that load latest version first - check if CommonLib is loaded into new app domain right before the call to Load.

    If it is the case you'll need to be very careful in linking your main code to CommonLib to avoid loading latest version too early. You may even need to use late binding/reflection for it.

    0 讨论(0)
  • 2020-12-10 10:04

    I think your problem is the following:

    Assembly asm = pluginDomain.GetAssemblies().First(a => a.GetName().Name == "Plugin");
    Type p = asm.GetTypes().First(t => t.GetInterfaces().Contains(typeof(IPlugin)));
    var pluginInstance = (IPlugin)pluginDomain.CreateInstanceAndUnwrap(asm.FullName, p.FullName);
    

    With this you're loading the updated/outdated type references into the main AppDomain (which has the assembly already loaded in a different version).

    I recommend you use the following approach:

    1. Create a separate assembly that contains the contracts/Interfaces. This Assembly is fixed and remains at a specific version all the time and it can never be outdated and each version of your plugin can reference it.
    2. Write an assembly loader that is part of your host application, but in a seperate assembly as well. This assembly loader assembly must not have any reference to the rest of your application so you can set it up in the new appdomain.
    3. After setting up the new appdomain, load an instance of your AssemblyLoader. This one loads the plugin assemblies and interacts with it.
    4. Your application doesn't interact with the assembly itself. Your application calls your AssemblyLoader via the appdomain boundary and the AssemblyLoader calls the Plugin

    I can't say if this is the best version possible, but this one works pretty well for me in an environment where each plugin can load any version of any assembly. With this setup you're pretty much resistant to changing versions or updates and each plugin can use the version it wants.

    Let me know if it works for you.

    0 讨论(0)
提交回复
热议问题