efcore.pg icon indicating copy to clipboard operation
efcore.pg copied to clipboard

Make NpgsqlDataSource a scoped service instead of singleton

Open roji opened this issue 1 year ago • 1 comments

NpgsqlDataSource is currently registered as a singleton service; although this conceptually makes sense, it creates various issues:

  • When automatically getting the data source from DI, there's no way in EF to include the data source instance in the decision-making on whether a new service provider is needed, causing interference between service providers (https://github.com/npgsql/efcore.pg/issues/2891).
  • In some multi-tenant and testing scenarios, it's desirable to use many data sources with potentially the same EF service provider. In the current situation, this requires lots of EF service providers, which triggers our "many service providers" warning.

The main thing blocking making NpgsqlDataSource scoped is the fact that we get enum mappings from it in NpgsqlTypeMappingSource, which is itself a singleton. We should stop doing that (#3063), at which point it should be easy to make NpgsqlDataSource scoped.

roji avatar Feb 09 '24 09:02 roji

Excellent! We're in that multi-tenant scenario. Despite careful re-use & disposal of the NpgsqlDataSoruce and DbContext instances, we still end up with that ManyServiceProvidersCreatedWarning error.

Here is the full error in case it helps others searching for solutions:

'Microsoft.EntityFrameworkCore.Infrastructure.ManyServiceProvidersCreatedWarning': More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework. This is commonly caused by injection of a new singleton service instance into every DbContext instance.

gbd3-en avatar Feb 15 '24 18:02 gbd3-en