编程语言
首页 > 编程语言> > 依赖注入ASP.NET Core:注册多个实现

依赖注入ASP.NET Core:注册多个实现

作者:互联网

我有以下类结构:

interface IContractService{}

class Service1 : IContractService{}

class Service2 : IContractService{}

class ContractServiceFactory
{
    private readonly IServiceProvider _serviceProvider;
     ContractServiceFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;            
    }
     IContractService GetContractService(string standard)
    {
        // Is it possible to retrieve service by string const???
        return _serviceProvider.GetRequiredService<IContractService>(standard);
    }
}

在服务集合中,我想通过以下方式添加类:

builder.Services.AddScoped<IContractService, ContractService1>("standard1");
builder.Services.AddScoped<IContractService, ContractService2>("standard2");

.net core 2.1是否可能?

解决方法:

对于这种复杂的注册,默认的开箱即用DI太简单了.它旨在满足框架和基于该框架构建的大多数消费者应用程序的基本需求.

因此,默认情况下您所需的功能不可用.

但是,该框架允许您使用功能良好的首选容器并替换默认容器.

官方文档在此处提供了一个示例

Dependency injection in ASP.NET Core: Default service container replacement

另一个选择可能是将设计更改为更加明确和牢固

interface IContractService{}

interface IContractService1: IContractService{}

interface IContractService2: IContractService{}

class ContractService1 : IContractService1{}

class ContractService2 : IContractService2{}

class ContractServiceFactory {
    private readonly IServiceProvider _serviceProvider;

    public ContractServiceFactory(IServiceProvider serviceProvider) {
        _serviceProvider = serviceProvider;            
    }

    public IContractService GetContractService(string standard) {
        switch(standard) {
            case "standard1" :
                return _serviceProvider.GetRequiredService<IContractService1>();
                break;
            case "standard2" :
                return _serviceProvider.GetRequiredService<IContractService2>();
                break;
            case .....
        }
    }
}

然后您相应地注册服务

builder.Services.AddScoped<IContractService1, ContractService1>();
builder.Services.AddScoped<IContractService2, ContractService2>();

标签:asp-net-core-2-1,asp-net-core,dependency-injection,c
来源: https://codeday.me/bug/20191108/2009340.html