Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Unity Error: Could not load file or assembly

I found this demo article on Unity. Looks pretty straightforward but I'm getting the following error:

Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, 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)

https://www.tutorialsteacher.com/ioc/register-and-resolve-in-unity-container

using System;
using Unity;

namespace UnityContainerDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<ICar, BMW>();// Map ICar with BMW 

            //Resolves dependencies and returns Driver object 
            Driver drv = container.Resolve<Driver>();
            drv.RunCar();
        }
    }

    public interface ICar
    {
        int Run();
    }

    public class BMW : ICar
    {
        private int _miles = 0;

        public int Run()
        {
            return ++_miles;
        }
    }

    public class Ford : ICar
    {
        private int _miles = 0;

        public int Run()
        {
            return ++_miles;
        }
    }

    public class Audi : ICar
    {
        private int _miles = 0;

        public int Run()
        {
            return ++_miles;
        }

    }
    public class Driver
    {
        private ICar _car = null;

        public Driver(ICar car)
        {
            _car = car;
        }

        public void RunCar()
        {
            Console.WriteLine("Running {0} - {1} mile ", _car.GetType().Name, _car.Run());
        }
    }
}
like image 821
Rod Avatar asked Jan 31 '19 21:01

Rod


Video Answer


2 Answers

Jasen is correct if your NuGet plays nicely with your project, but I wasn't so lucky (when I tried re-adding the package, I got the same error).

What fixes the bug is adding a dependentAssembly entry for the 'missing' assembly inside your app/web config (which is the magic behind the NuGet install, and should happen automatically).

<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> ...

like image 91
Brad Lucas Avatar answered Nov 12 '22 07:11

Brad Lucas


When I attempted to duplicate the problem, the error went away after I ran a NuGet update for System.Runtime.CompilerServices.Unsafe.

like image 32
Jasen Avatar answered Nov 12 '22 07:11

Jasen