Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Initialize SDK clients and connections

A worked example

Single answer

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:

  1. The process must use exactly one CosmosClient for its whole lifetime.
  2. The first incoming request must not pay the connection setup and routing discovery cost.
  3. The client must be disposed when the host stops.

How should you create and register the client in Program.cs?

Choose one answer
Why

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 CreateAndInitializeAsync for product inside each request handler, wrapped in a using declaration. 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 CreateAndInitializeAsync for product, register it with AddSingleton(client), and keep its using scope alive until the host stops. CreateAndInitializeAsync prefetches routing metadata at startup, one instance is shared, and the using scope disposes the existing instance when the host stops.
  • Not correct: Register AddSingleton<CosmosClient> with a factory delegate that constructs the client and calls GetContainer for product. GetContainer is 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 CreateAndInitializeAsync for product, register it with AddSingleton(client), and add no shutdown code. An existing instance registered with AddSingleton(client) is not disposed by the host; disposal remains the caller's responsibility.
  • Not correct: Register AddSingleton<CosmosClient> with a factory delegate that calls the CosmosClient constructor, 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.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free