Skip to content

InvalidOperationException: More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework #34918

@blink2linkme

Description

@blink2linkme

Ask a question : InvalidOperationException: More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework.

I am trying to work with PostgreSQL Enum Data Types using Npgsql and have added the NpgsqlDataSourceBuilder to my existing code. While registering the service for the Database Context, I am encountering the following warning:

More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework.

Include your code

Startup.cs

var dataSourceBuilder = new NpgsqlDataSourceBuilder();
var connectionString = configuration.GetConnectionString("NpgConnectionString");
services.AddDbContext<ApplicationDbContext>((provider, options) =>
{
    var dbCredentials = provider.GetRequiredService<HashicorpVaultService>().GetCredentials();
    dataSourceBuilder.ConnectionStringBuilder.ConnectionString = connectionString.Replace("Username", dbCredentials.Username).Replace("Password", dbCredentials.Password) ?? throw new Exception("DB Connection String Invalid");
    dataSourceBuilder.MapEnum<Status>("Status");
    var dataSource = dataSourceBuilder.Build();

    options.UseNpgsql(dataSource);
});

Include Stack Trace

System.InvalidOperationException: 'An error was generated for warning '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. For example, calling 'UseLoggerFactory' passing in a new instance each time--see https://go.microsoft.com/fwlink/?linkid=869049 for more details. This may lead to performance issues; consider reviewing calls on 'DbContextOptionsBuilder' that may require new service providers to be built. This exception can be suppressed or logged by passing event ID 'CoreEventId.ManyServiceProvidersCreatedWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

Include provider and version information

Database provider : Npgsql: 8.0.4, Npgsql.EntityFrameworkCore.PostgreSQL: 8.0.8
Target framework: (.NET 8.0)
Operating system:
IDE: (Visual Studio 2022 17.11.4)

Additional Context
I suspect that the way I am configuring the NpgsqlDataSourceBuilder might be causing multiple IServiceProvider instances to be created. How can I resolve this issue?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions