Azure / azure-cosmos-dotnet-v3

.NET SDK for Azure Cosmos DB for the core SQL API
MIT License
723 stars 479 forks source link

Improve client initialization ergonomics #4404

Open onionhammer opened 2 months ago

onionhammer commented 2 months ago

This could be improved quite a lot; realistically people aren't running async calls when they're initializing their ServiceProvider; making the CreateAndInitializeAsync API quite awkward to use in practice.

How it is now

serviceBuilder.AddSingleton(services =>
{
  return CosmosClient.CreateAndInitializeAsync(...containers...).GetAwaiter().GetResult();
});

A better option would be

serviceBuilder.AddSingleton(services =>
{
  var client = new CosmosClient(...);
  _ = client.InitializeAsync(... containers ...);
  return client;
});

Separating out creation from the initialization.

@ealsur @j82w @Maya-Painter

Originally posted by @onionhammer in https://github.com/Azure/azure-cosmos-dotnet-v3/issues/1706#issuecomment-2049827703

waszakCeneo commented 2 months ago

You still need to await InitializeAsync

onionhammer commented 2 months ago

@waszakCeneo you do, if you want to throw/catch exceptions with await

image

RobARichardson commented 1 week ago

This could be improved quite a lot; realistically people aren't running async calls when they're initializing their ServiceProvider; making the CreateAndInitializeAsync API quite awkward to use in practice.

Recently used this feature of the SDK and I had the same thought. I ended up doing CosmosClient.CreateAndInitializeAsync(...).GetAwaiter().GetResult() when registering CosmosClient as a singleton which feels dirty.

You still need to await InitializeAsync

This is true, however an instance member that performs the initialization would allow a consuming application to relocate the initialization logic from DI registration to somewhere during Application Startup.