[TypeLoadException: Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.] System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0 System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +180 System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +192 System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +115 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +426 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103 System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit) +64 WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly assembly) +132 WebActivator.ActivationManager.RunActivationMethods() +216 WebActivator.ActivationManager.RunPreStartMethods() +43 WebActivator.ActivationManager.Run() +69
原因: In .Net 4.5 theExtensionAttribute
class was moved from System.Core to mscorlib.
ExtensionAttribute
類在4.5中從System.Core遷移到mscorlib中,項目運行時會按4.5的方法尋找導致異常。
有人會說,項目都是按4.0編譯的,4.5也卸載了,為什么還會出現此問題?原因在於引用的第三方類庫可能還是關聯的4.5版本,比如我遇到這個問題是由於Entityframework引用了4.5版本導致的,而4.0和4.5從dll屬性中看不出來
參考:
http://www.cnblogs.com/gossip/p/3527970.html
http://stackoverflow.com/questions/13748055/could-not-load-type-system-runtime-compilerservices-extensionattribute-from-as
http://stackoverflow.com/questions/16039990/runtime-exception-with-net-4-5-build-could-not-load-type-system-runtime-compi
解釋:System.Runtime.CompilerServices.ExtensionAttribute 在 .net 4.0里 在 System.Core.Dll里, 在 .net 4.5里則被移到了 mscorlib 中。
System.Core.Dll的版本顯示的 4.0.0.0 版,但實際上已經被 .net 4.5替換,里面沒有ExtensionAttribute 類。
未替換的版本在目錄“C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0”下,用Reflector可以看到,里面有ExtensionAttribute類。
解決的方法:
解決方法1: 在用戶的機器上安裝 .net 4.5。 對OS的要求是:
Windows 7 SP1(x86 和 x64)
Windows Server 2008 R2 SP1 (x64)
Windows Server 2008 SP2(x86 和 x64)
解決方法2: 自己編譯混淆的機器上,僅安裝了.net 4.0, 未安裝 4.5。
后記:把 4.5卸載后, 重新安裝了 4.0, 問題復現。再次發布程序,問題解決。