Add a context option to allow reusing the same service provider (disabling caching)
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
EF has an internal caching mechanism for its internal service providers; this caching mechanism relies on being able to compare the context options which are specified by the user, and when these vary in a way which makes service provider sharing impossible, EF automatically creates a new service provider internally.
For example, the Cosmos provider exposes various context options for user configuration, which correspond to low-level Cosmos SDK options: HttpClientFactory, ConnectionMode, etc. When users initialize these to different values, EF automatically creates different service providers, since the CosmosClient built from these options must be a singleton.
This is an inherently problematic design, since it requires that EF be able to compare all context options. For Cosmos, this means that EF cannot accept a ready-made CosmosClient or CosmosClientOptions, since these are opaque and can't be compared for equality (see #35482). As a result, we've painted ourselves into a corner where we duplicate low-level Cosmos options at the EF level, simply so that we can reliably compare them. Of course, we're behind on some newer options which aren't exposed to users.
To get out of this place, we can introduce a new context option to opt into bypassing the cache checks and reusing the internal service provider. This would allow us to simply disregard the user-configured CosmosClient (for the purposes of service provider caching); this should take care of the 95% case, where the application only uses a single CosmosClient anyway.
Note that the same situation exists in the PostgreSQL provider, where we have NpgsqlDataSource; though DbDataSource is a general ADO.NET concept, and fully bringing it to EF would require solving this problem for relational provider as well.
For more complicated scenarios where multiple CosmosClients are actually needed, we'd have to start going in the direction of #35481, where only the user is in charge of specifying when a service provider is reused, via the factory APIs.
Contributor guide
Assessment
This issue has not been assessed yet.