2011-09-23 87 views
1

我有一個應用程序參考Microsoft.Data.SqlXml.dll程序集(部分SQLXML)。但是在不同的機器上,取決於它是實時環境還是測試,還是開發人員本地PC,安裝了不同版本的SQLXML。這就產生了一個問題:根據目標機器,我必須編譯應用程序,以防止正確的Microsoft.Data.SqlXml.dll程序集。動態程序集選擇和運行時加載

在Subversion中,我保留在實時環境中使用的csproj和dll文件。當我必須在本地測試利用Microsoft.Data.SqlXml.dll的模塊時,我在項目中更改了引用,並將其還原回來。但有好幾次我忘了回滾更改,並且我檢查了csproj和Microsoft.Data.SqlXml.dll,其版本不符合SQLXML安裝在活動服務器上。結果,我收到運行時錯誤。

我的問題是:有沒有辦法在運行時動態加載程序集?我可以在應用程序的某個地方使用switch語句,根據app.config中的條目載入正確的程序集(例如。env =「live | test | local」)?或者也許有另一種方法來解決這個問題?

謝謝你,帕維爾

+2

確保您的參考文獻中的特定版本設置爲false – Guillaume

回答

1

從微軟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

+0

謝謝!還有一個問題:我仍然在csproj中引用設置爲特定版本的DLL:。如果我在live env的3.0版本中加載程序集,它會起作用嗎? – dragonfly

+0

@dragonfly:做Guillaume告訴你的:「確保你的參考文獻中的特定版本設置爲false」 – Marco