Search code examples
c#dllbindingdependenciestypeloadexception

System.TypeLoadException occurs on duplicate dependency with different version


I have a C# Solution with several C# projects inside.

One project depends on two dlls which itself depend on the same dll but different version like shown here:

Project -> dll1.dll -> System.IdentityModel.Tokens.Jwt.dll (Version=5.4.0.0) 
Project -> dll2.dll -> System.IdentityModel.Tokens.Jwt.dll (Version=4.0.4.4)

Now when I use dll2.dll it throws this exception:

System.TypeLoadException: 'Could not load type 'System.IdentityModel.Tokens.JwtSecurityTokenHandler' from assembly 'System.IdentityModel.Tokens.Jwt, Version=5.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.'

I read about AutoGenerateBinding and tried to set it to True and to False, but both resulted in exceptions. I lack the experience how to handle such a case and need advice / good articles about how to resolve such a conflict. What is a good approach, if I neither have control over the implementation of dll1.dll or dll2.dll?

Is there a clean solution to this problem?

Edit:

I added an binding redirect like suggested to all usages of this dll in my projects and installed via nuget in all the same version:

<dependentAssembly>
    <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.20622.1351" newVersion="4.0.20622.1351" />
  </dependentAssembly>

Still the same exception is thrown, it seems that the requirement from the referenced dll somehow overwrites the requirement from my project. I set the build info verbose level to detailed, so during rebuild I get this output: enter image description here

Is there away to avoid that my wish for the exact version via the bindingRedirect is overwritten?

Solved: Solved it like described here stackoverflow. I removed all Nuget packages and linked to the same dll which is referenced by dll1. And additionally I removed all binding redirects and set AutoGenerateBindings to False in the project settings.


Solution

  • The best solution is to avoid this. We spend considerable time updating all projects to use the same version of a dll. However, if you cannot avoid it, you can use Binding Redirects to control in a very detailed way:

    <runtime>
       <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
           <dependentAssembly>
              <assemblyIdentity name="System.Web.Http" publicKeyToken="31BF3856AD364E35" culture="neutral" />
              <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
           </dependentAssembly>
       </assemblyBinding>
    </runtime>