Dynamic assembly selection and loading in runtime
I have an application that has reference to Microsoft.Data.SqlXml.dll assembly (part of SQLXML). But on different machines, depending on whether it's live environment or test, or developers local PC, different versions of SQLXML are installed. This arises an issue: depending on destination machine I have to compile application against correct Microsoft.Data.SqlXml.dll assembly.
In Subversion I keep csproj and dll file that is used on live environment. When I have to test modules that take advantage of Microsoft.Data.SqlXml.dll locally, I change reference in project, and revert them back. But several times I forgot to rollback changes and I checked in csproj and Microsoft.Data.SqlXml.dll with version that didn't comply with SQLXML installed on live server. As a result, I received runtime errors.
My question is: is there any way to dynamically load assemblies i开发者_运维知识库n runtime? I can have switch statement somewhere in application that would load correct assembly depending on entry in app.config (eg. env="live|test|local") ? Or perhaps there is another way to address this issue?
Thanks,Pawel
From Microsoft page:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
private Assembly MyResolveEventHandler(object sender,ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.
//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly,objExecutingAssemblies;
string strTempAssmbPath="";
objExecutingAssemblies=Assembly.GetExecutingAssembly();
AssemblyName [] arrReferencedAssmbNames=objExecutingAssemblies.GetReferencedAssemblies();
//Loop through the array of referenced assembly names.
foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(","))==args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath="C:\\Myassemblies\\"+args.Name.Substring(0,args.Name.IndexOf(","))+".dll";
break;
}
}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);
//Return the loaded assembly.
return MyAssembly;
}
Naturally you have to change the part //Build the path of the assembly
using what you need.
精彩评论