繁体   English   中英

无法加载文件或程序集

[英]Could not load file or assembly

我正在重构一个 ASP.Net Core 2.2 webapp。 我决定将一些功能移到一个单独的 class 库(.net core 2.2)项目中。 class 库依赖于 System.IO.Abstractions(因此可以进行单元测试)。 class 库的简化版本如下所示:

using System;
using System.IO.Abstractions;

namespace ClassLibrary1
{
    public class TestService
    {
        private IFileSystem fileSystem;

        internal TestService(IFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        public TestService() : this(new FileSystem()) {}
    }
}

在 web 应用程序项目中,我添加了对 class 库 dll 的引用。 在 Startup.cs 中,我添加了 using 语句,在 ConfigureServices 中,我正在使用 DI 容器注册 TestService(在 class 库中定义):

 ...
using ClassLibrary1;

namespace WebApplication1
{
    public class Startup
    {
        ...

        public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddScoped<TestService>();
        }

        ...
    }
}

我正在尝试在 controller 中实例化服务,如下所示:

using ClassLibrary1;

namespace WebApplication1.Controllers
{    
    public class HomeController : Controller
    {
        TestService service;

        public HomeController(TestService service)
        {
            this.service = service;
        }

        ...
    }
}

当我运行这个项目时,我收到以下错误:

FileNotFoundException:无法加载文件或程序集“System.IO.Abstractions,版本=7.0.0.0,文化=中性,PublicKeyToken=96bf224d23c43e59”。 该系统找不到指定的文件。

如何在不将 System.IO.Abstractions package 添加到 webapp 项目的情况下解决此问题?

我的理解是问题的出现是因为我试图使用 DI 解决的 class 的构造函数包含 IFileSystem 类型,这是一个外部依赖项,因此 webapp 无法解决它。

在四处寻找解决此问题的方法后,我尝试做的一件事是向 class 库添加扩展方法,该方法负责注册所需的依赖项:

using Microsoft.Extensions.DependencyInjection;
using System.IO.Abstractions;

namespace ClassLibrary1
{
    public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddTestService(this IServiceCollection services)
        {
            services.AddScoped<IFileSystem, FileSystem>();
            services.AddScoped<TestService>();

            return services;
        }
    }
}

然后在 webapp 的 ConfigureServices 中使用这个扩展方法,如下所示:

services.AddTestService();

但是,这会导致相同的错误消息。

编辑:

我真正的问题是如何正确编写 class 库,以便可以使用它而不必担心依赖关系?

因此,在 webapp 中,应该使用公共无参数构造函数来实例化 TestService,而在 xunit 项目的 classlib 解决方案中,可以使用内部构造函数来实例化 TestService。

您不应该解决 class 库中的依赖关系。 组合根只能在主应用程序中。 组合根是应用程序生命周期中可以设置 object 图的起点和最早点。

所以Startup.cs是 ASP.NET 核心应用程序中的组合根。

services.AddScoped<IFileSystem, FileSystem>();

Class 库没有组合根。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM