Could not load file or assembly System.Runtime.CompilerServices.Unsafe
Asked Answered
L

16

101

I created a Visual Studio (Community 2019) project with C# using ServiceStack.Redis. Since it is C#, I use Windows 10 (there is a Redis version for Windows but it is really old and as I know, it is unofficial so I am afraid that might be the problem). Here is an excerpt from my code:

public class PeopleStorage: IDisposable
{
    public PeopleStorage()
    {
        redisManager = new RedisManagerPool("localhost");
        redis = (RedisClient)redisManager.GetClient();
        facts = (RedisTypedClient<List<Fact>>)redis.As<List<Fact>>();
    }

    public List<Fact> GetFacts(int id)
    {
        string sid = id.ToString();
        if (facts.ContainsKey(sid))
            return facts[sid];
        return accessor.GetFacts(id);
    }

    private RedisTypedClient<List<Fact>> facts;
    private RedisClient redis;
    private RedisManagerPool redisManager;
}

In an attempt to connect to Redis in line return facts[sid];, an exception occurs:

System.IO.FileLoadException: "Could not load file or assembly "System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" or one of it's dependences. The found Assembly's manifest definition does not match the Assembly reference. (Exception from HRESULT: 0x80131040)"

(May be inaccurate as I have translated it)

I have tried updating all the packages, starting with ServiceStack packages, ending with System.Runtime.CompilerServices.Unsafe itself. Moreover, you can't choose 4.0.4.1 version in NuGet, the closest one there is 4.0.0, while the relevant is 4.0.7.

I do not understand why it uses this version and how I can fix this problem.
Even a clean reinstall of Visual Studio did not help.

Locality answered 6/7, 2020 at 21:25 Comment(3)
Which version of ServiceStack.Redis did you use?Padrone
Did you use a net framework console project or net core console project?Padrone
Same problem here using System.Text.Json v 5.0.0. I think that NuGet package has broken dependencies.Faints
P
109

Could not load file or assembly System.Runtime.CompilerServices.Unsafe

It seems that you have installed System.Runtime.CompilerServices.Unsafe nuget package 4.5.3 version. And it corresponds to System.Runtime.CompilerServices.Unsafe.dll assembly version 4.0.4.1.

Suggestion

1) Please try to register System.Runtime.CompilerServices.Unsafe version 4.0.4.1 into GAC so that the system can it.

  • Run Developer Command Prompt for VS2019 as Administrator

  • type:

    cd xxxxx (the path of the the System.Runtime.CompilerServices.Unsafe 4.0.4.1)
    
    gacutil /i System.Runtime.CompilerServices.Unsafe.dll
    

2) If you use Net Framework projects with xxx.config file, you could use bindingRedirect.

Add these in app.config file or web.config file:

<configuration>  
   <runtime>  
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
         <dependentAssembly>  
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe"  
                              publicKeyToken="b03f5f7f11d50a3a"  
                              culture="neutral" />  
            <bindingRedirect oldVersion="0.0.0.0-4.0.4.1"  
                             newVersion="4.0.4.1"/>  
         </dependentAssembly>  
      </assemblyBinding>  
   </runtime>  
</configuration> 

Besides, if you update System.Runtime.CompilerServices.Unsafe nuget package version to the newer version, you should also changed the bindingRedirect assembly version.

You can refer to these assembly versions of System.Runtime.CompilerServices.Unsafe

NuGet package version Assmbly version
4.5.0, 4.5.1, 4.5.2 4.0.4.0
4.5.3 4.0.4.1
4.6.0 4.0.5.0
4.7.0, 4.7.1 4.0.6.0
5.0.0 5.0.0.0
Padrone answered 7/7, 2020 at 7:51 Comment(14)
So I did not really understand your explanation since i have tried using both 4.0.7 and 4.5.3 packages but your first suggestion worked, thank you! Although now I can't try the second one... P.S. need 2 more points to upvotethis answer :(Locality
#1 suggestion worked for me too. I wonder why it has to be cached on my other laptop since everything's working well with my main laptop.Basidiospore
4.7.0 is 4.0.6.0, where did you find this mapping? Did you download them one by one, and check it by tools like dnSpy?Fanion
Thanks, solution 2 worked for me, but I think there is a mistake in your snippet. It should be publicKeyToken="b03f5f7f11d50a3a"Biddable
@StefanoAltieri, thanks for pointing that. And I will update it.Padrone
how does one even find the assembly version?Haile
I am on NuGet.org, right now... That is NOT what I am seeing... 4.52 of Nuget Package has 4.6.28619.1 as DLL version.Cyathus
To find the version yourself, go to "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" where v10.0A could be a different number so check first. There you will find ildasm.exe. Start it and open the dll you wanna check the version for.Discovery
You can use Nuget Package explorer to discover assembly versions.Piggott
After 4 hours of back and forth, installing EXACTLY 4.5.3 did it for me after seeing this comment.Foodstuff
This worked, but then we get a similar error on System.Buffers, once we figured that out, then this error came back... full circle. App.config seems to make no difference, are there any requirements on app.config - ie compiled as "content" or some specific output?Tyndall
the solution 1 worked for me you may need to run it in one line though gacutil /i ...packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dllBleacher
I am suddenly getting this error now. See: github.com/jstedfast/MailKit/issues/1492. But, I have Unsafe version 6.0.0.0. Not sure what to do.Synopsize
For me, it seems that upgrading Mimekit from 3.4.2 to 3.4.3 causes this error. If I revert Mimekit back to 3.4.2 I do not get the error.Synopsize
A
45

I assume that you're using the .NET Framework. This error is known for ServiceStack.Redis and is tracked on GitHub. It occurs because you use libraries that depend on different versions of System.Runtime.CompilerServices.Unsafe. These transitive dependencies need to be resolved and consolidated to end up with one assembly in your output folder. You will end up with the latest of these versions. Consequently, if one of the libraries depends on a specific version that is older, it will not be found.

The bug that causes this issue is fixed in System.Runtime.CompilerServices.Unsafe 4.6.0. Use binding redirects, to load the specific version of the assembly that you need. Insert this snippet into all of your app.config files.

<dependentAssembly>
    <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>

You need to specify the assembly version of the assembly that you need as newVersion. This is not the same as the package version that you choose when installing your NuGet package. They correspond like this:

  • Package 4.5.3 contains assembly version is 4.0.4.1
  • Package 4.7.0 contains assembly version 4.0.6.0

In this binding redirect I use the newer version of System.Runtime.CompilerServices.Unsafe that fixes the bug. However, if you depend on the older version, use 4.0.4.1.

Archpriest answered 7/7, 2020 at 6:58 Comment(1)
As I have posted elsewhere.. THose are NOT the .dll versions I am seeing in the respective niget packages...Cyathus
G
16

My problem was solved by deleting the "bin" and "obj" folders.

Galactic answered 22/2, 2022 at 11:16 Comment(0)
S
14

Based on Perry's answer, I simply installed the nuget package System.Runtime.CompilerServices.Unsafe version 4.5.3 and the problem was solved.

Shakitashako answered 27/5, 2021 at 16:4 Comment(0)
A
13

In my case I installed the latest 6.0.0.0 package across my solution (including the net 472 web apps!) and then added a binding redirect to version 6


      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
Ahrendt answered 14/10, 2022 at 18:51 Comment(0)
H
10

My app is a native EXE which loads .NET assemblies; we have no app.config file. Assembly config files are not loaded and used at runtime. So the approach I took to solve this was based on helpful answers here and here.

The idea is to catch the assembly load exception and handle it by substituting whatever existing (higher versioned) System.Runtime.CompilerServices.Unsafe assembly is already loaded.

Add this somewhere early in application startup:

AppDomain.CurrentDomain.AssemblyResolve += 
    new ResolveEventHandler(CurrentDomain_AssemblyResolve);

And this is the event handler:

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var name = new AssemblyName(args.Name);
    if (name.Name == "System.Runtime.CompilerServices.Unsafe")
    {
        return typeof(System.Runtime.CompilerServices.Unsafe).Assembly;
    }
    return null;
}

This worked great in my situation. I also happen to think this is a little more discoverable than potentially cryptic settings in app.config (IMO) so it might be a good solution in general.

Hominoid answered 30/9, 2022 at 22:0 Comment(2)
Worked for me! Native application as well using CLI.Sogdian
In my case I had to do the following trick since the file is in the same folder already and I do not want an app.config file: if (name.Name == "System.Memory") return Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System.Memory.dll"));Brancusi
B
5

I had different versions of the System.Runtime.CompilerServices.Unsafe nuget package installed across different projects. I updated all to use version 6.0.0 and that resolved the issue.

Billibilliard answered 10/5, 2023 at 21:0 Comment(1)
Same thing worked for me when I faced this error trying to use Parquet.net. I upgraded CompilerService.Unsafe to v6.0.0 from v4.5.3.Browne
D
4

In my experience, I didn't need to install System.Runtime.CompilerServices.Unsafe because it is referenced from another package, npgsql. Instead, what I did is as follow:

  1. Insert this code snippet to app.config of the project
 <configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.1.4.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>
  1. Run again the project

This is the solution I found so far, to add dependentAssembly bindingReference

Delitescent answered 6/4, 2021 at 6:56 Comment(0)
N
4

Recently I encountered exactly the same error message. However, that message did not appear in all PCs that I used to test my app. Some PCs yielded the error message but some others are not. I couldn't differentiate which are the characteristics of PC that would be generating error message and which ones did not. It seemed.. random.

Then I noticed a warning message when I compiled my app (I was using Visual Studio 2019 at the time):

Severity Code Description Project File Line Suppression State Warning Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190. SQL Online Exam System

And I did exactly what it told me:

enter image description here

Then the problem was solved.

Neuburger answered 5/1, 2022 at 17:1 Comment(0)
R
1

In my case, the package/assembly reference entry was not present in the web.config file at all.

Reest answered 28/3, 2023 at 10:45 Comment(0)
C
1

I encountered this when running unit tests (using MSTest); the application itself had no issue. It was fixed by adding this line to the unit test .csproj, in the first <PropertyGroup>:

<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

My environment: VS2022 and .NET Framework 4.8

Cortney answered 11/12, 2023 at 19:50 Comment(0)
I
0

Thanks @thatguy finally was able to resolve the issue.

The solution that worked for me was from Nick Craver with details as below:

Things to try:

** Reference the System.Runtime.CompilerServices.Unsafe library directly as a (so VS alerts it needs a binding and offers a one-click fix...sometimes it won't realize this transitively).

** If using app.config, remove all binding redirects and add a true property up on the top.


This is a load errors and I really really really wish they had a wiki page explaining how to fix this because it can plague any library anyway if you step on one of the magical landmines.

Inoperative answered 1/6, 2022 at 8:25 Comment(0)
B
0

In my case, a Visual Studio update helps.

Baa answered 5/9, 2022 at 10:5 Comment(0)
C
0

In my case, everything was working but I started getting this message after a merge.

None of the solutions worked because everything was setup correctly. My dll version was 6.0, so I downgraded to 5.0, ran the project (successfully) and then upgraded to 6.0 and then ran it again. Worked perfectly.

Hope this helps someone.

Cinchona answered 5/10, 2022 at 2:28 Comment(0)
D
0

In my case, I had the latest EntityFramework6.Npgsql but older Npgsql package which caused the issue. Updating NpgSql package fixed the issue.

Danube answered 11/7, 2023 at 11:25 Comment(0)
I
0

I got the similar error many times. Any of the above solutions did not work. The solution that worked was as suggested i this article [https://learn.microsoft.com/en-us/answers/questions/1302681/could-not-load-file-or-assembly-system-runtime-com]

Please try to download the Nuget package from System.Runtime.CompilerServices.Unsafe After downloading, you will get a .nupkg file, move it to a clean folder. Rename the file extension to .zip, open it, open the lib folder, open the net461 folder and you should see the dll file, copy the folder path, let’s say the path is C:\XXXX\XXXX.

Run Developer Command Prompt for Visual Studio as administrator, and run following commands:

cd C:\XXXX\XXXX

gacutil /i System.Runtime.CompilerServices.Unsafe.dll

Now you no more need any binding redirects in your solution.

Inoperative answered 30/11, 2023 at 4:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.