Great tutorial. I do have a question though. I saw you've added a singleton for the specific class. What to do if I have another service class and want to use CosmosClient on that class as well? Do I create another singleton class for that newly created class, on Program.cs??
Thanks for your comments The best approach is not to create another singleton for the newly created class. Instead, you can reuse the CosmosClient singleton instance across different service classes Example public class AnotherService { private readonly CosmosClient _cosmosClient; public AnotherService(CosmosClient cosmosClient) { _cosmosClient = cosmosClient; } // Use _cosmosClient for database operations }
@@DigitalTECHJOINT Thank you for the response. Not sure this is the right channel to ask, but I added the CosomClient as Singleton on Program.cs builder.Services.AddSingleton((provider) => { var cosmosClient = new CosmosClient(builder.Configuration["ConnectionStrings:CosmosDB"]); return new ConsumerRepository(cosmosClient); //return cosmosClient; }); Now, I don't want the client to be tied to object ConsumerRepository. But whenever I remove the object and instead return the client only,i get DI error. If you could help, would be great. A code sample would be awesome.Just starting out, so a bit of novice in this case, apologies in advance for being bothersome. Thank you.
Great tutorial. I do have a question though. I saw you've added a singleton for the specific class. What to do if I have another service class and want to use CosmosClient on that class as well? Do I create another singleton class for that newly created class, on Program.cs??
Thanks for your comments
The best approach is not to create another singleton for the newly created class. Instead, you can reuse the CosmosClient singleton instance across different service classes
Example
public class AnotherService
{
private readonly CosmosClient _cosmosClient;
public AnotherService(CosmosClient cosmosClient)
{
_cosmosClient = cosmosClient;
}
// Use _cosmosClient for database operations
}
@@DigitalTECHJOINT Thank you for the response. Not sure this is the right channel to ask, but I added the CosomClient as Singleton on Program.cs
builder.Services.AddSingleton((provider) =>
{
var cosmosClient = new CosmosClient(builder.Configuration["ConnectionStrings:CosmosDB"]);
return new ConsumerRepository(cosmosClient);
//return cosmosClient;
});
Now, I don't want the client to be tied to object ConsumerRepository. But whenever I remove the object and instead return the client only,i get DI error.
If you could help, would be great. A code sample would be awesome.Just starting out, so a bit of novice in this case, apologies in advance for being bothersome.
Thank you.