我有一个引用Microsoft.Data.SqlXml.dll程序集(SQLXML的一部分)的应用程序。但是在不同的机器上,取决于它是运行环境还是测试环境,或者是开发人员的本地PC,会安装不同版本的SQLXML。这就产生了一个问题:根据目标机器,我必须针对正确的Microsoft.Data.SqlXml.dll程序集编译应用程序。
在Subversion中,我保留了在活动环境中使用的csproj和dll文件。当我必须在本地测试利用Microsoft.Data.SqlXml.dll的模块时,我更改项目中的引用,并将它们还原回来。但是有几次我忘记回滚更改,我检查了csproj和Microsoft.Data.SqlXml.dll,版本不符合安装在实时服务器上的SQLXML。结果,我收到了运行时错误。
我的问题是:是否有任何方法在运行时动态加载程序集?我可以有开关语句在应用程序的某个地方,将加载正确的程序集取决于在app.config(例如。env = "生活| |测试本地")?或者也许有另一种方法来解决这个问题?
谢谢,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;
}
当然,你必须改变部分//Build the path of the assembly
使用你需要的。