Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a binding redirect at runtime?

Once an application has started is there a way to create a binding redirect that will apply to all future assembly loads?

like image 348
Simon Avatar asked Apr 13 '11 08:04

Simon


People also ask

What is binding redirect Visual Studio?

1 use automatic binding redirection. This means that if two components reference different versions of the same strong-named assembly, the runtime automatically adds a binding redirection to the newer version of the assembly in the output app configuration (app. config) file.

Why does Nuget add binding redirects?

Binding redirects are added if your app or its components reference more than one version of the same assembly, even if you manually specify binding redirects in the configuration file for your app.


2 Answers

Sorry for responding to an old post, but this blog has a much better answer to the question. Hope someone finds it useful.

My use case: doing a binding redirect from a COM interop assembly invoked by a classic ASP application.

http://blog.slaks.net/2013-12-25/redirecting-assembly-loads-at-runtime/

This function from the post in question will do what you want:

public static void RedirectAssembly(string shortName, Version targetVersion, string publicKeyToken) {
    ResolveEventHandler handler = null;

    handler = (sender, args) => {
        // Use latest strong name & version when trying to load SDK assemblies
        var requestedAssembly = new AssemblyName(args.Name);
        if (requestedAssembly.Name != shortName)
            return null;

        Debug.WriteLine("Redirecting assembly load of " + args.Name
                      + ",\tloaded by " + (args.RequestingAssembly == null ? "(unknown)" : args.RequestingAssembly.FullName));

        requestedAssembly.Version = targetVersion;
        requestedAssembly.SetPublicKeyToken(new AssemblyName("x, PublicKeyToken=" + publicKeyToken).GetPublicKeyToken());
        requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;

        AppDomain.CurrentDomain.AssemblyResolve -= handler;

        return Assembly.Load(requestedAssembly);
    };
    AppDomain.CurrentDomain.AssemblyResolve += handler;
}
like image 151
Bryan Slatner Avatar answered Oct 05 '22 11:10

Bryan Slatner


It could be possible using ICLRHostBindingPolicyManager::ModifyApplicationPolicy, but I've never tried myself. Note that this is a CLR-level interface, so you can't load policies for individual AppDomains (which is why it is not used by PostSharp yet).

http://msdn.microsoft.com/en-us/library/ms164378.aspx

like image 37
Gael Fraiteur Avatar answered Oct 05 '22 10:10

Gael Fraiteur