今天遇到一個奇怪問題,有一個ASP.NET項目,訪問時總是顯示不能加載EF4.1的錯誤(項目中對EF的引用都已升級至EF5.0):
Could not load file or assembly 'EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
說明: 執行當前 Web 請求期間,出現未經處理的異常。請檢查堆棧跟蹤信息,以了解有關該錯誤以及代碼中導致錯誤的出處的詳細信息。
異常詳細信息: System.IO.FileLoadException: Could not load file or assembly 'EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
源錯誤:
執行當前 Web 請求期間生成了未經處理的異常。可以使用下面的異常堆棧跟蹤信息確定有關異常原因和發生位置的信息。
程序集加載跟蹤: 下列信息有助於確定程序集“EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”未能加載的原因。
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
問題怪就怪在我找遍整個項目的代碼,也沒找到哪個地方引用了Entity Framework 4.1.0.0。
后來,注意到錯誤信息中的提示——“dTo enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1”,想到是不是可以通過日志找出究竟哪個地方引用了EF 4.1。進入注冊表一看,有HKLM\Software\Microsoft\Fusion,但沒有HKLM\Software\Microsoft\Fusion!EnableLog。不知該如何下手?
在網上搜了搜,在stackoverflow上發現How to enable assembly bind failure logging (Fusion) in .NET的回答:
Add the following values to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
String LogPath set value to folder for logs ie) C:\FusionLog\
於是在注冊表進行了這樣的設置:
然后再訪問,在頁面顯示的錯誤信息中包含了下面一行:
Calling assembly : Devtalk.EF.CodeFirst, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
在C:\FusionLog\Default\64baea7c中也可以找到對應的日志文件EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.HTM
於是,真相大白——這個項目中引用了Devtalk.EF.CodeFirst.dll,而它引用了Entity Framework 4.1,從而引起這個問題。
更新:
如果不想生成日志文件,只想在錯誤信息中顯示“Calling assembly”,只需要在注冊表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion中將LogResourceBinds的值設置為1(DWORD(32-bit))。
注:修改注冊表之后需要重啟IIS才能生效