如何更新运行时assemblyBinding在配置文件部分?配置文件、部分、assemblyBinding

2023-09-03 03:48:02 作者:抖落一身扎人的谎

我试图改变组件动态绑定(从一个版本到另一个版本)。

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

我已经试过这code,但它不工作:

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. HTH