Is it possible to create a binding redirect at runtime?

笑着哭i 提交于 2019-12-21 17:34:42

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/5646306/is-it-possible-to-create-a-binding-redirect-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!