Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Assembly Binding Redirection to ignore revision and build numbers

I have several .NET applications in C#, along with an API for them to access the database. I want to put all versions of the API in the database, and have them pick the highest revision and build number, but stick with the major and minor number they were built with. Basically when I reference API 1.2.3.4 I want the reference to read 1.2.*.* so that the applications just pick up 1.2.3.5 I see I can do this with XML config files. I'd rather have it complied in. Similar to publish policies, but with out the extra files. I could settle for that. The other issue is all solutions I see redirect one version to another specific version, not just to any version newer.

How do I do this?

Can someone point me to an informative source for publisher policy?

like image 421
Anthony D Avatar asked Sep 22 '09 13:09

Anthony D


People also ask

How does binding redirect work?

1 or a later version, the app uses 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.

How do I stop auto-generate binding redirects?

Right-click the project in Solution Explorer and select Properties. On the Application page, uncheck the Auto-generate binding redirects option. If you don't see the option, you'll need to manually disable the feature in the project file.

What is Post policy reference?

My understanding is that "Post-policy reference" is the assembly reference after publisher policies, and in general assembly redirections, have occured.


1 Answers

Thanks to leppie's suggestion of using the AppDomain.AssemblyResolve event, I was able to solve a similar problem. Here's what my code looks like:

    public void LoadStuff(string assemblyFile)
    {
        AppDomain.CurrentDomain.AssemblyResolve += 
            new ResolveEventHandler(CurrentDomain_AssemblyResolve);
        var assembly = Assembly.LoadFrom(assemblyFile);

        // Now load a bunch of types from the assembly...
    }

    Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        var name = new AssemblyName(args.Name);
        if (name.Name == "FooLibrary")
        {
            return typeof(FooClass).Assembly;
        }
        return null;
    }

This completely ignores the version number and substitutes the already loaded library for any library reference named "FooLibrary". You can use the other attributes of the AssemblyName class if you want to be more restrictive. FooClass can be any class in the FooLibrary assembly.

like image 189
Don Kirkby Avatar answered Oct 21 '22 07:10

Don Kirkby