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

11

149

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'.
Magistery answered 6/12, 2012 at 16:27 Comment(3)
We need more context about where you're starting your web site, and how. Are you definitely using .NET 4/4.5?Unarm
NB: if anyone has the same symptoms on output from your build server check that you have the .net 4.0 reference assemblies, after installing .net 4.5 you'll need to copy them from your dev box. These are typically somewhere like: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 For more details see marcgravell.blogspot.co.nz/2012/09/…Korwun
I've just seen a similar issue with a .NET 4.5 DLL being used as a plugin for Microsoft Dynamics CRM 2011 on a machine which only had .NET 4.0. Rather than just rejecting it outright, it registered it and then completely broke workflow customisation (the plugin contained a custom workflow activity). Trace showed that it couldn't find ExtensionAttribute in mscorlib, led me here, rebuilt it for .NET 4.0 and problem solved! Thought that should be mentioned for future Google-fu.Augend
A
265

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.

Anabal answered 6/12, 2012 at 18:29 Comment(17)
I'm getting all the same symptoms, but I'm not using ILMerge, any clues? stacktrace here issues.umbraco.org/issue/U4-1708, it could be a 3rd or 4th party DLL, but how do I find it?Korwun
Note: You may not have a "C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" folder in case of 64 bit windows versions, in that case check if you have a "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" folder.Colonnade
I didn't install ILMerge and I have this problem, so how can I fix it? Do I have to install .net 4.5 on the target server?Cowbell
Could this also happen if there are 2.0/3.5 dll's being used alongside an ilmerge'd 4.0 dll?Infantry
@Hans-Passant: Does this solution apply for the server as well, cause I have the same error, not on my local but on the server?Maple
Yes, the version of .NET that's installed on the machine that has the broken project matters. Works by accident if it 4.0, won't work if it is 4.5Anabal
Could you clarify this sentence? "But absolutely essential now that 4.5 is released." I'm building on 4.5, targeting 4.0/4.5. I'm not using ILMerge, just Visual Studio. Do you mean that the problem is that I'm using classes or methods that were added after 4.0, and that if I remove those references, the problem will be resolved?Welles
This is a great breakdown of the issue. More than a year later and 4.5.1 just reached our build machine via an auto-update (we've since disabled auto updates). Am I understanding right that there is still no solution from MS, other than avoiding having 4.5 on the machine altogether? Installing 4.5 on all end-user's machines isn't an option for us & doesn't seem like a good solution when our application is 4.0.Carry
It is bewildering to me why everybody keeps insisting that this is something that MS should solve. They won't, they can't fix your broken projects or build servers. Use the correct reference assemblies, problem solved.Anabal
Could this error happen for different reason than unmatching versions of the assembly?Sauna
If an MS update caused working builds (on updated machines) to fail on non-updated machines one can reasonably interpret that as a mistake. I can certainly imagine there would be ways MS could fix it. Whether we should expect they will is another question, but is Hans Passant honestly "bewildered"? The entire issue is bewildering and I am struggling in vain still to find a solution to this problem. Use the correct reference assemblies: how? Suddenly what I never dreamed would fail, fails. If I'm targeting 4.0 I expect it to work on 4.0. We did not break this and the fix is NOT simple.Carry
Actually, the multi-targeting packs download was a sufficient solution. Probably something that should've been included in the 4.5.1 auto-deploy since it IS the fix I was expecting MS to provide, and they did provide because they saw the problem they'd created. Problem was masked for me by SmartAssembly which arbitrarily un-fixes what the multi-targeting packs fixed. So we are forced to make sure clients update to 4.5.1 anyways.Carry
What happens when i run ilmerge with /v4 would that generate a valid or invalid assembly?Louden
very nice explanation !!Runofthemill
NuGet 2.8.6 has this problem; it was built targeting .NET 4.5 and uses the wrong ILMerge option.Leakage
God Bless you! My target machine was running 4.0 but the dev machine was 4.5. Just updated my target machine to 4.5 and voila!Brothers
I'm updating some old C++/CLI code and went from Visual Studio 2010 (projects were 4.0) to 2015 (taking small steps) and it auto-updated to 4.5.2 as part of the conversion process. I had to down-grade to 4.0 for the time being, but the resultant project changes referenced mscorlib, but not System.Core. This answer got things cleared up!Aesthesia
S
11

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.

Sulphurate answered 26/11, 2013 at 20:56 Comment(0)
I
8

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>
Instalment answered 12/2, 2014 at 19:36 Comment(0)
D
6

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.

Diaster answered 14/2, 2014 at 1:43 Comment(1)
Advance warning for you, EVEN IF you resolve the issue otherwise, your obfuscated version will be broken again, so you may never know you resolved it. That is, you CAN build on 4.5 and deploy without trouble to 4.0-only machines. All that was necessary for me was the multi-targeting patch Hans Passant mentions. I could see from looking at the manifest in ILDASM that it was correctly targeting System.Core instead of mscorlib. But NOT on the version that had been run through SmartAssembly (v5.5).Carry
C
4

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

Cantle answered 26/11, 2013 at 12:18 Comment(1)
man, thanks, i ran into the same problem, how did you fix it?Ineptitude
S
3

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.

Storage answered 4/6, 2014 at 16:45 Comment(1)
In our case the problem was caused by Quartz.NET v2.3. Upgrading to version 2.3.2 fixed the problem.Passage
M
2

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"

Medulla answered 3/7, 2014 at 19:57 Comment(0)
F
1

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

Folacin answered 19/10, 2015 at 12:55 Comment(0)
C
1

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.

Cindycine answered 17/8, 2016 at 2:4 Comment(0)
C
1

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" />
Colo answered 20/2, 2018 at 8:21 Comment(0)
P
0
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.

Peter answered 25/9, 2021 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.