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

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

问题描述

我的 .NET 应用程序有不同版本的 dll,大多数时候我想使用最新版本.但是,我在单独的线程上运行了一种方法,我需要能够根据某些条件选择旧版本的 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天全站免登陆