C# Unity 错误:无法加载文件或程序集

问题描述 投票:0回答:4

我在 Unity 上找到了这篇演示文章。看起来很简单,但我收到以下错误:

无法加载文件或程序集 'System.Runtime.CompilerServices.Unsafe,版本=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' 或其之一 依赖关系。找到的程序集的清单定义不 匹配装配参考。 (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());
        }
    }
}
c# unity-container
4个回答
10
投票

如果你的 NuGet 与你的项目配合得很好,Jasen 是正确的,但我没那么幸运(当我尝试重新添加包时,我得到了同样的错误)。

修复该错误的方法是为应用程序/Web 配置中“丢失”的程序集添加 dependentAssembly 条目(这是 NuGet 安装背后的魔力,应该自动发生)。

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


4
投票

当我尝试复制问题时,在运行

System.Runtime.CompilerServices.Unsafe
的 NuGet 更新后错误消失了。


1
投票

就我而言,我的解决方案中有几个项目。我在其中一个项目中使用 Nuget 安装 Unity,而在另一个项目中安装 Unity 后,出现了该错误。 问题来自不同版本的 CompilerServices.Unsafe 库

我所做的是检查所有安装了 Unity 的项目的 app.config 和 packcages.config 文件(特别是这个)。所有人的版本应该相同。就我而言:

<packages>
  <package id="System.Runtime.CompilerServices.Unsafe" version="4.7.0" targetFramework="net48" />
  <package id="Unity" version="5.11.2" targetFramework="net48" />
</packages>

一个项目使用 4.7.0,另一个项目使用 4.5 我更新到最新版本并解决了。

您还可以右键单击解决方案 - 管理解决方案的 Nuget 包并安装一个包,只需一步即可选择哪些项目将拥有该包。


0
投票

您可以在

web.config
文件中手动添加依赖项,然后查看其工作情况。在您的
web.config
文件中添加以下依赖项:

<dependentAssembly>
    <assemblyIdentity name="Unity.Abstractions" publicKeyToken="489b6accfaf20ef0" />
    <bindingRedirect oldVersion="0.0.0.0-5.11.6.0" newVersion="5.11.7.0" />
</dependentAssembly>
© www.soinside.com 2019 - 2024. All rights reserved.