【问题标题】:How to inject by DI two objects that are of the same type but have one property different?如何通过 DI 注入两个相同类型但具有不同属性的对象?
【发布时间】:2021-02-12 03:19:39
【问题描述】:

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

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

然后在我注入的类中:

public CosmosService(CosmosClient cosmosClient, CosmosClient bulkCosmosClient)

问题是如何区分一个和另一个?

【问题讨论】:

标签: c# .net-core dependency-injection asp.net-core-5.0


【解决方案1】:

在您的情况下,最简单的方法是使用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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多