Simon
Simon

Reputation: 34880

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?

Upvotes: 11

Views: 3062

Answers (2)

Bryan Slatner
Bryan Slatner

Reputation: 1608

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;
}

Upvotes: 13

Gael Fraiteur
Gael Fraiteur

Reputation: 6857

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

Upvotes: 2

Related Questions