Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

.Net

.Net Problem Overview


When starting up my web site for the first time, I'm getting this error

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

What am I doing wrong?

I am using .NET 4 and am starting the site from Visual Studio.

The only thing I've changed recently is add Simple Injector (via Nuget) into my project.

Here's the stack trace

[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

[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +423
   System.Web.Compilation.BuildManager.CallPreStartInitMethods() +306
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +677

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258

The first line of all views get highlighted and when you hover over them you get this error

The pre-application start initialisation method Run on type WebActivator.ActivationManager threw an exception with the following error message Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

.Net Solutions


Solution 1 - .Net

> Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib

Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.

As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:

  /targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"

Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:

  /targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"

So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.


Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.

Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.

Solution 2 - .Net

I had this problem, except the type it couldn't load was System.Reflection.AssemblyMetadataAttribute. The web application was built on a machine with .NET 4.5 installed (runs fine there), with 4.0 as the target framework, but the error presented itself when it was run on a web server with only 4.0 installed. I then tried it on a web server with 4.5 installed and there was no error. So, as others have said, this is all due to the screwy way Microsoft released 4.5, which basically is an upgrade to (and overwrite of) version 4.0. The System.Reflection assembly references a type that doesn't exist in 4.0 (AssemblyMetadataAttribute) so it will fail if you don't have the new System.Reflection.dll.

You can either install .NET 4.5 on the target web server, or build the application on a machine that does not have 4.5 installed. Far from an ideal resolution.

Solution 3 - .Net

I had this exact same problem with a site (Kentico CMS), starting development in 4.5, finding out the production server only supports 4.0, tried going back down to target framework of 4.0. Compiling the other posts in this thread (specifically changing target framework to .Net 4 and .Net 4.5 still being referenced). I searched through my solution and found that a handful of the NuGet packages were still using libraries with targetFramework="net45".

packages.config (before):
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AutoMapper" version="3.1.0" targetFramework="net45" />
  <package id="EntityFramework" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.0.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>

I changed the projects target framework back to 4.5, removed all NuGet libraries, went back down to 4.0 and re-added the libraries (had to use some previous versions that were not dependent on 4.5).

packages.config (after):
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AutoMapper" version="3.1.1" targetFramework="net40" />
  <package id="EntityFramework" version="6.0.2" targetFramework="net40" />
  <package id="Microsoft.AspNet.WebApi.Client" version="4.0.30506.0" targetFramework="net40" />
  <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net40" />
  <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40" />
</packages>

Solution 4 - .Net

I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.

I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.

Solution 5 - .Net

I did encounter the same problem while trying to read data from a Firebird Database. After many hours of searching, I found out that the problem was caused by an error I made in the query. Fixing it made it work perfectly. It had nothing to do with the version of the Framework

Solution 6 - .Net

We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).

The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.

It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.

Solution 7 - .Net

In my case after downgrading from .NET 4.5 to .NET 4.0 project was working fine on a local machine, but was failing on server after publishing.

Turns out that destination had some old assemblies, which were still referencing .NET 4.5.

Fixed it by enabling publishing option "Delete all existing files prior to publish"

Solution 8 - .Net

In my case, it was Blend SDK missed out on TeamCity machine. This caused the error due incorrect way of assembly resolving then.

Solution 9 - .Net

Just adding this answer to help Google save some punter the hours I have spent to get here. I used ILMerge on my .Net 4.0 project, without the /targetplatform option set, assuming it would be detected correctly from my main assembly. I then had complaints from users only on Windows XP aka WinXP. This now makes sense as XP will never have > .Net 4.0 installed whereas most newer OSes will. So if your XP users are having issues, see the fixes above.

Solution 10 - .Net

In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb line in web.config and it started working:

<system.web>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  

Solution 11 - .Net

AppendTargetFrameworkToOutputPath false

A different edge case...

If you are using the AppendTargetFrameworkToOutputPath property and setting to false, then copying multiple assemblies that are targeting different platforms, you may get this message. Basically, the framework dependencies are in conflict.

use AppendTargetFrameworkToOutputPath true (or just remove) or ensure all output modules are targeting the same framework.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachin KainthView Question on Stackoverflow
Solution 1 - .NetHans PassantView Answer on Stackoverflow
Solution 2 - .NetEricPView Answer on Stackoverflow
Solution 3 - .NetvandshView Answer on Stackoverflow
Solution 4 - .NetProfessor1942View Answer on Stackoverflow
Solution 5 - .Netuser3036330View Answer on Stackoverflow
Solution 6 - .NetDavid YatesView Answer on Stackoverflow
Solution 7 - .NetAlexander PuchkovView Answer on Stackoverflow
Solution 8 - .NetYury SchkatulaView Answer on Stackoverflow
Solution 9 - .NetLMKView Answer on Stackoverflow
Solution 10 - .NetMatthew LockView Answer on Stackoverflow
Solution 11 - .NetJahmicView Answer on Stackoverflow