Search code examples
c#entity-frameworkasp.net-core.net-core

multiple parameter on DatabaseContext class constructor


I want to inject and use ILogger from DatabaseContext in asp.net core. And I want to manage the context using a Contextpool. However, when I try to inject two dependencies including Ilogger, I get the following error.

The DbContext of type 'DatabaseContext' cannot be pooled because it does not have a public constructor accepting a single parameter of type DbContextOptions or has more than one constructor.

How can I get an Ilogger injected?

This is my database context classes constructor

public class DatabaseContext : DbContext
{
    private readonly ILogger _logger;
 
    
    public DatabaseContext(DbContextOptions<DatabaseContext> options, ILogger<DatabaseContext> logger) : base(options)
    {
        _logger = logger;
    }
}

and setting database context pool setting code on program.cs

builder.Services.AddDbContextPool<DatabaseContext>((provider,options) =>
{
    options.UseSqlServer(appConfiguration.GetConnectionString("DatabaseConnection"))
        .EnableSensitiveDataLogging()
        .EnableDetailedErrors();
});

Solution

  • If you are using the AddDbContextPool, you should query the required services instead of injecting it.

    More details, you could refer to below codes:

       public class ApplicationDbContext : IdentityDbContext
       {
           private readonly ILogger _logger;
    
           public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options )
               : base(options)
           {
               _logger = this.GetService<ILogger<ApplicationDbContext>>();
               _logger.LogError("test");
           }
    
       }
    

    Result:

    enter image description here