An ASP.NET Core minimal API uses the Microsoft.Azure.Cosmos .NET SDK with DefaultAzureCredential to read items from the product container in the cosmicworks database. Requirements:
- The process must use exactly one
CosmosClientfor its whole lifetime. - The first incoming request must not pay the connection setup and routing discovery cost.
- The client must be disposed when the host stops.
How should you create and register the client in Program.cs?
Only CosmosClient.CreateAndInitializeAsync performs connection setup and routing discovery for the listed containers before any request arrives. Because the finished instance is registered with AddSingleton(client), the host will not dispose it, so the using scope must stay alive until the host stops and then dispose the client. A DI factory would be disposed automatically but defers the setup cost to the first request.
- Not correct: Create a client with
CreateAndInitializeAsyncforproductinside each request handler, wrapped in ausingdeclaration. A client per request discards the connection pool and routing cache each time and breaks the one-client-per-account singleton guidance. - Correct: Create it with
CreateAndInitializeAsyncforproduct, register it withAddSingleton(client), and keep itsusingscope alive until the host stops. CreateAndInitializeAsync prefetches routing metadata at startup, one instance is shared, and theusingscope disposes the existing instance when the host stops. - Not correct: Register
AddSingleton<CosmosClient>with a factory delegate that constructs the client and callsGetContainerforproduct.GetContaineris a zero-network call that returns a logical handle, so it warms nothing, and the deferred factory still leaves connection setup to the first request. - Not correct: Create it with
CreateAndInitializeAsyncforproduct, register it withAddSingleton(client), and add no shutdown code. An existing instance registered withAddSingleton(client)is not disposed by the host; disposal remains the caller's responsibility. - Not correct: Register
AddSingleton<CosmosClient>with a factory delegate that calls theCosmosClientconstructor, and add no shutdown code. The factory defers construction, and the .NET constructor makes no network calls, so the first request that uses Azure Cosmos DB pays for connection setup and routing discovery.