1

I'm trying to inject two singleton Cosmos clients that are the same in all senses except for a property that changes their behavior but I need both. This is how I'm adding them in Startup:

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

Then in the classes I'm injecting as:

public CosmosService(CosmosClient cosmosClient, CosmosClient bulkCosmosClient)

The problem is how do I differentiate one from the other?

user33276346
  • 1,501
  • 1
  • 19
  • 38
  • 1
    Does this answer your question? [Dependency injection of multiple instances of same type in ASP.NET Core 2](https://stackoverflow.com/questions/46476112/dependency-injection-of-multiple-instances-of-same-type-in-asp-net-core-2) – gunr2171 Feb 11 '21 at 17:04
  • Can you differentiate them by interface? Register one of them as ICosmosClient, and another one as IBulkCosmosClient – user2363676 Feb 11 '21 at 17:07
  • @user2363676 Unfortunately Cosmos is an external library. – user33276346 Feb 11 '21 at 17:14

1 Answers1

0

The easiest way in your case would be using the IEnumerable<CosmosClient>:

public CosmosService(IEnumerable<CosmosClient> bulkCosmosClient)

Extended sample:

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);
    }
}

enter image description here

enter image description here

Boris Sokolov
  • 1,723
  • 4
  • 23
  • 38