Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.1.0.0

I have a .NET Standard 1.4 class library that references the System.ComponentModel.Annotations (4.3.0) NuGet package.

I'm then referencing this class library from a .NET Framework 4.6.2 test project. It builds fine, but at runtime I get the following error:

System.IO.FileLoadException occurred HResult=0x80131040
Message=Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I tried adding a reference to the System.ComponentModel.Annotations (4.3.0) NuGet package from the net462 project, but that didn't make any difference.

I tried adding a reference to the .NET Standard library from the net462 project, but still no luck.

Am I missing something here? Is this a known bug, if so is there a work around?

Any help is much appreciated!

like image 427
Dan Ellis Avatar asked May 18 '17 16:05

Dan Ellis


2 Answers

In many cases, this can be solved by adding the following code to the csproj file of your test project:

<PropertyGroup>   <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>   <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> </PropertyGroup> 

This forces the build process to create a .dll.config file in the output directory with the needed binding redirects.

The reason is that "classic" csproj test projects are true "libraries" and are not considered to need binding redirects by default. But running unit tests requires this. This only becomes an issue if referenced projects need those redirects to work correctly. This usually works when directly installing all NuGet packages that the referenced library uses, but with the new PackageReference style of NuGet packages, it does not.

See other instances where this fix has helped:

Could not load file or assembly Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.1.0.0

When using .Net Standard 1.4 in a library and .Net framework 4.6.1 in and application, unable to load file System.IO.FileSystem, Version=4.0.1.0

like image 176
Martin Ullrich Avatar answered Oct 03 '22 22:10

Martin Ullrich


I had similar problem but none of the above answers helped me. It turns out that solution is very easy, I've just run following command in Package Manager:

Install-Package System.ComponentModel.Annotations -Version 4.1.0

like image 20
Lukasz Cokot Avatar answered Oct 03 '22 23:10

Lukasz Cokot