Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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");

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
256 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...