How to use Assembly Binding Redirection to ignore revision and build numbers
Asked Answered
S

2

18

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?

Spacetime answered 22/9, 2009 at 13:57 Comment(0)
G
34

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.

Greenroom answered 26/2, 2010 at 20:30 Comment(2)
I'm trying to do this in the context of an ASP.NET application. Where might I hook into the AppDomain.CurrentDomain.AssemblyResolve event? At an application event level (i.e. global.asax)?Uxmal
I think you should be able to register for the AssemblyResolve event from anywhere. There's nothing special about the LoadStuff() method. If you decide to register for the event each time you load an assembly, just remember to unregister when you're done.Greenroom
V
5

AppDomain.AssemblyResolve event should help.

Valley answered 25/9, 2009 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.