AppDomain.CurrentDomain.AssemblyResolve :: Different Assembly version numbers causes casting to fail

Few days ago, I came across a problem with the MbUnit code that I was looking over to get an idea of the architecture.

The problem was that when the reference to the mbunit.framework in the project you are testing is different that the reference in the exe the application would crash with a random error message.

The section of code which causes a problem was when it tried to cast a type from one assembly into a type from another assembly. Due to them having different version numbers, they are treated as completely different types and cannot be cast between the two. This happened since we started to sign the assembly, as before, unsigned assemblies do not worry about the version number and treat everything as the same.

After a few hours, I found a cool event on the AppDomain object called AssemblyResolve. When a different assembly is loaded in the application with a different version type, the event is fired and calls this section of code:

private Assembly AssemblyResolveHandler(object sender,ResolveEventArgs e)

{
try
{
string[] assemblyDetail = e.Name.Split(‘,’);
string assemblyBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFrom(assemblyBasePath + @”” + assemblyDetail[0] + “.dll”);
return assembly;
}
catch (Exception ex)
{
throw new ApplicationException(“Failed resolving assembly”, ex);
}
}

This takes in the assembly Full Name (e), and loads the assembly name from file making sure that the latest assembly is always loaded. This seemed to have solved the problem with MbUnit, as it protects against people having old references in there project.

Just thought it was a good code snippet.

Leave a Reply

Your email address will not be published. Required fields are marked *