Hi,
The am using .Net SDK version 3 in my .Net 6 web api. This is used to establish connection with the backend cosmos db. AS per the Performance tips and guidelines, Its mentioned to have a singleton instanse of a cosmos client for the application lifecycle. in Order to achieve the above I have registered a cosmos service as singelton in the program.cs as below
builder.Services.AddSingleton<ICosmosService, CosmosService>();
Then in the cosmos service class the connection is initialised as below
private static readonly CosmosClient? cosmosClient;
static CosmosService()
{
cosmosClient =SetCosmosConnectionProperties(); // Initializes the cosmos client object
}
public static CosmosClient SetCosmosConnectionProperties()
{
List<string> cosmosRegion = new List<string>();
cosmosRegion.Add(ConfigValues.CosmosPreferredRegion);
foreach (string s in ConfigValues.CosmosOtherRegions.Split(','))
{
cosmosRegion.Add(s);
}
var cosmosConnectionProperties = GetCosmosConnection(); //Sets Containers and DB name for Cosmos client
CosmosClientOptions options = new CosmosClientOptions();
options.ApplicationName = ConfigValues.ApplicationName;
options.ApplicationPreferredRegions = cosmosRegion;
options.ConnectionMode = ConnectionMode.Direct;
return new CosmosClient(EndPointUri,PrimaryKeyReadOnly, options);
}
//The dependency is inject in controller class as below
private ICosmosService cosmosService { get; }
public DemoController(ICosmosService _cosmosService)
{
cosmosService =_cosmosService
}
//Then in the api action method use the connection as below
[Route("[action]")]
[HttpGet]
public async Task<ObjectResult> GetData(string appName)
{
using (var _cosmosClient = cosmosClient)
{
//Use the cosmos client to fetch data from Cosmosbackend
}
}
This works as expected for the first api call, however for the second call it throws the cosmosClient is disposed error in the using block.
Not sure why the object is getting disposed here? Other singelton initilization works as expected not sure whats the case with CosmosClient here.