在.NET Core WebApp中构建服务层。构造函数DI不工作

时间:2017-12-22 14:44:39

标签: c# entity-framework .net-core constructor-injection

我想在我的.NET Core WebApp中实现一个服务层,但是我对构造函数依赖注入有一些问题,并且不知道我做错了什么。也许有人可以告诉我我的错误。

关于服务的想法是他们拥有业务逻辑,并且是唯一与存储库对话的人。由于事实每个服务都有自己的责任,他们不仅要与他们的存储库说话,还要与其他服务部门说话,具体取决于必须完成哪个业务任务。

要做到这一点,我首先注册我的存储库,如下所示:

Startup.cs

public void ConfigureServices(IServiceCollection services) {
    this.storageConnectionString = "Server=.;Initial Catalog=MyDatabase;Integrated Security=True;";
    services.AddScoped<IDeviceRepository>(r => new EntityDeviceRepository(this.storageConnectionString));
    services.AddScoped<IMasterDataRepository>(r => new EntityMasterDataRepository(this.storageConnectionString));
    ...

(在相同的文件和功能中)我注册我的服务:

    var serviceProvider = services.BuildServiceProvider();
    services.AddScoped<IDeviceService>(r => new DeviceService(
        serviceProvider.GetService<IDeviceRepository>(),
        serviceProvider.GetService<IMasterDataRepository>(),
        ));

    services.AddScoped<IHardwareDataService>(r => new HardwareDataService(
        serviceProvider.GetService<IDeviceService>(),
        serviceProvider.GetService<IHardwareDataRepository>()
        ));
    ...
}

IHardwareDataService.cs

public interface IHardwareDataService
{
    Task<Boolean> UpdateHardwareData(HardwareData hardwareData);
}

HardwareDataService.cs

public class HardwareDataService : BaseService, IHardwareDataService
{
    private IDeviceService deviceService;
    private IHardwareDataRepository hardwareDataRepository;

    public HardwareDataService(IDeviceService deviceService, IHardwareDataRepository hardwareDataRepository)
    {
        this.deviceService = deviceService;
        this.hardwareDataRepository = hardwareDataRepository;
    }

    public async Task<Boolean> UpdateHardwareData(HardwareData hardwareData)
    {
        // Create the Device via the Device Service if not already existing (Business Logic)
        // Update Hardware Data of Device (Business Logic + direct Access via HWDataRepository)
    }
}

问题

&#34; IDeviceService&#34;工作没有问题。 &#34; IHardwareDataService&#34;不。确切地说,对象&#34; IDeviceService&#34;是null

似乎我无法通过构造函数依赖注入向另一个服务提供服务,但我不明白为什么以及如何使其成为正确的方式。

关于如何解决这个问题的任何提示?

2 个答案:

答案 0 :(得分:4)

在这种情况下,确实没有必要构建提供程序。

查看您注册服务的方式,可以简化为......

services.AddScoped<IDeviceService, DeviceService>();
services.AddScoped<IHardwareDataService, HardwareDataService>();

在解析实现时,框架将注入必要的依赖项。

参考:Introduction to Dependency Injection in ASP.NET Core: Registering Your Own Services

答案 1 :(得分:2)

尝试替换

data

 var serviceProvider = services.BuildServiceProvider();
    services.AddScoped<IDeviceService>(r => new DeviceService(
        serviceProvider.GetService<IDeviceRepository>(),
        serviceProvider.GetService<IMasterDataRepository>(),
        ));

    services.AddScoped<IHardwareDataService>(r => new HardwareDataService(
        serviceProvider.GetService<IDeviceService>(),
        serviceProvider.GetService<IHardwareDataRepository>()
        ));