所以這個專案一執行就發生 System.TypeLoadException 的錯誤,如下,
無法從組件 'myDLL, Version=2.0.3500.9, Culture=neutral, PublicKeyToken=5298a1bd3421ecdc' 載入型別 'myDLL.newFeature'。

查看 Publisher Policy 中的 bindingRedirect 設定是從 2.0.0.0-2.0.65535.65535 都是是使用 2.0.3500.9 這個版本(一般會是取 組件名.config ),
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myDLL" publicKeyToken="5298a1bd3421ecdc" culture="neutral" /> <bindingRedirect oldVersion="2.0.0.0-2.0.65535.65535" newVersion="2.0.3500.9"/> </dependentAssembly> </assemblyBinding> </runtime></configuration>
所以就會 Load 到 GAC 中的 DLL , 而不是在 bin 目錄的 2.0.3500.10 這一版。那要怎麼辦呢?
測試發現,只需要設定 bindingRedirect 及設定 publisherPolicy apply 為 no ,如下,
雖然專案使用的是新版本的(2.0.3500.10),但因為 GAC 有,所以系統還是會先從 GAC 去 Load 進來(詳細可以參考Assemblies: locating, binding and deploying),所以還是會發生錯誤!
所以我們的專案需要在 config 檔(app.config or web.config)中設定讓它 binding 到新的版本,如下,
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myDLL" publicKeyToken="5298a1bd3421ecdc" culture="neutral" /> <bindingRedirect oldVersion="2.0.3500.10" newVersion="2.0.3500.10"/> <publisherPolicy apply="no" /> </dependentAssembly> </assemblyBinding></runtime>
這樣就可以讓目前這個專案使用Bin目錄的新的版本,而不會使用到 GAC 的舊版本DLL。
參考資訊
Assemblies: locating, binding and deployingHow to: Create a Publisher Policy
本文也發表於亂馬客Blog