如何在运行时更新配置文件中的 assemblyBinding 部分? [英] how to update assemblyBinding section in config file at runtime?

查看:25
本文介绍了如何在运行时更新配置文件中的 assemblyBinding 部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态更改程序集绑定(从一个版本到另一个版本).

I'm trying to change assembly binding (from one version to another) dynamically.

我已经尝试过这段代码,但它不起作用:

I've tried this code but it doesn't work:

      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"];

      assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml";
      config.Save(ConfigurationSaveMode.Modified);

      ConfigurationManager.RefreshSection("assemblyBinding");

使用 bindingConf.xml 包含 assemblyBinding 部分配置.

with bindingConf.xml containing the assemblyBinding section configuration.

那么可以在运行时更改此部分吗?怎么做?我有哪些选择?

So can a change this section at runtime? how to do it? What alternatives do I have?

推荐答案

我发现动态绑定到不同版本的程序集的最佳方法是挂钩 AppDomain.AssemblyResolve 事件.每当运行时无法找到应用程序链接到的确切程序集时,就会触发此事件,并且它允许您提供另一个程序集,您自己加载,在它的位置(只要它兼容).

The best way I've found to dynamically bind to a different version of an assembly is to hook the AppDomain.AssemblyResolve event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible).

例如,您可以在应用程序的主类上放置一个静态构造函数,它可以像这样挂钩事件:

For example, you can put in a static constructor on your application's main class that hooks the event like this:

using System.Reflection;

static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
    {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "AssemblyNameToRedirect")
        {
            // Put code here to load whatever version of the assembly you actually have

            return Assembly.LoadFrom("RedirectedAssembly.DLL");
        }
        else
        {
            return null;
        }
    };
}

这种方法不需要处理配置文件中的程序集绑定,并且在您可以使用它做什么方面更加灵活.

This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.

这篇关于如何在运行时更新配置文件中的 assemblyBinding 部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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