如何通过 DI 注入两个类型相同但有一个 属性 不同的对象?

How to inject by DI two objects that are of the same type but have one property different?

我正在尝试注入两个在所有方面都相同的单例 Cosmos 客户端,除了 属性 会改变它们的行为,但我需要两者。这就是我在 Startup 中添加它们的方式:

        services.AddSingleton(new CosmosClientBuilder(CosmosConnStr))
            .Build());
        services.AddSingleton(new CosmosClientBuilder(CosmosConnStr))
            .WithBulkExecution(true)
            .Build());

然后在 类 我注入为:

public CosmosService(CosmosClient cosmosClient, CosmosClient bulkCosmosClient)

问题是如何区分两者?

在您的情况下,最简单的方法是使用 IEnumerable<CosmosClient>:

public CosmosService(IEnumerable<CosmosClient> bulkCosmosClient)

扩展示例:

public class CosmosClient
{
    public string Connection;

    public CosmosClient(string v)
    {
        this.Connection = v;
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddSingleton(new CosmosClient("AA"));
    services.AddSingleton(new CosmosClient("BB"));
}

[ApiController]
[Route("[controller]")]
public class CosmosController : ControllerBase
{
    private readonly IEnumerable<CosmosClient> _bulkCosmosClient;

    public CosmosController(IEnumerable<CosmosClient> bulkCosmosClient)
    {
        _bulkCosmosClient = bulkCosmosClient;
    }

    public IActionResult Index()
    {
        List<string> list = new List<string>();
        foreach (var c in _bulkCosmosClient)
        {
            list.Add(c.Connection);
        }

        return new JsonResult(list);
    }
}