Skip to content

AddDbContext doesn't provide a LoggerFactory on the CoreOptionsExtension. #23329

@qsdfplkj

Description

@qsdfplkj

I want to use the LoggerFactory from the CoreOptionsExtension .

public class MyContext : DbContext
{
    private readonly ILogger<MyContext> logger;

    public MyContext(DbContextOptions options) : base(options)
    {
        logger = options.FindExtension<CoreOptionsExtension>()?.LoggerFactory?.CreateLogger<MyContext>();
        if (logger == null)
        {
            throw new Exception("Logger required.");
        }
    }
}

This will throw the exception:

services.AddDbContext<MyContext>();

This does work but then the documentation states:

//     There is no need to call this method when using one of the 'AddDbContext' methods,
//     including 'AddDbContextPool'. These methods ensure that the Microsoft.Extensions.Logging.ILoggerFactory
//     used by EF is obtained from the application service provider.

services.AddDbContext<MyContext>((serviceProvider, optionsBuilder) =>
{
    optionsBuilder.UseLoggerFactory(serviceProvider.GetService<ILoggerFactory>());
});

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