我如何切换.NET程序集执行一种方法呢?程序、方法、NET

由网友(怕你无动于衷)分享简介:我有不同版本的DLL我的.NET应用程序,大部分的时间,我想用最新的一个。然而,有一个方法,我运行一个单独的线程,我需要能够选择的dll基于某些条件的旧版本。I have different versions of dlls for my .NET application and most of the time I...

我有不同版本的DLL我的.NET应用程序,大部分的时间,我想用最新的一个。然而,有一个方法,我运行一个单独的线程,我需要能够选择的dll基于某些条件的旧版本。

I have different versions of dlls for my .NET application and most of the time I want to use the latest one. However, there is one method which I run on a separate thread where I need to be able to select an older version of the dll based on some criteria.

据我了解,这是不可能的,只是加载程序集,然后默认应用程序域中卸载它(我不能只保留两个版本加载,因为那时我快到类型的重复定义的问题)

I have learned that it is not possible to just load an assembly and then unload it within the default application domain (I can't just keep both versions loaded because then I'm running into duplicate definitions of types problem)

也许我要创建一个单独的AppDomain,加载程序集那里,然后卸载它。此应用程序域将在单独的线程中执行只有一个方法和将与不同版本的库。

Probably I have to create a separate AppDomain, load the assembly there and then unload it. This application domain would execute just one method on a separate thread and would work with a different version of the library.

你认为这是一个很好的方法/有你更好的想法/你能指点这将让我开始有些源?

Do you think it is a good approach / have you better ideas / can you point me to some source which would get me started ?

非常感谢;)

推荐答案

尝试是这样的:

class Program
{
    static void Main(string[] args)
    {
        System.Type activator = typeof(ApplicationProxy);
        AppDomain domain = 
            AppDomain.CreateDomain(
                "friendly name", null,
                new AppDomainSetup()
                {
                    ApplicationName = "application name"
                });

        ApplicationProxy proxy = 
            domain.CreateInstanceAndUnwrap(
                Assembly.GetAssembly(activator).FullName,
                activator.ToString()) as ApplicationProxy;

        proxy.DoSomething();

        AppDomain.Unload(domain);
    }
}

和创建一个代理类(必须继承 MarshalByRefObject的

And create a proxy class (must inherit from MarshalByRefObject)

class ApplicationProxy : MarshalByRefObject
{
    public void DoSomething()
    {
        Assembly oldVersion = Assembly.Load(new AssemblyName()
        {
            CodeBase = @"c:yourfullpathAssemblyFile.dll"
        });

        Type yourOldClass = oldVersion.GetType("namespace.class");
        // this is an example: your need to correctly define parameters below
        yourOldClass.InvokeMember("OldMethod", 
                                   BindingFlags.Public, null, null, null);
    }
}
阅读全文

相关推荐

最新文章