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 high
AppDomain.AssemblyResolve
event should help.
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.