我如何切换.NET程序集执行一种方法呢? [英] How can I switch .NET assembly for execution of one method?

查看:118
本文介绍了我如何切换.NET程序集执行一种方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同版本的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:\yourfullpath\AssemblyFile.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);
    }
}

这篇关于我如何切换.NET程序集执行一种方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆