Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inheriting DbContext with default options or without them should have the same behavior #33578

Closed
michaeltg17 opened this issue Apr 19, 2024 · 1 comment
Labels
closed-no-further-action The issue is closed and no further action is planned. customer-reported

Comments

@michaeltg17
Copy link

When creating the AppDbContext and inheriting from DbContext, you can pass the default options to DbContext using DI like this:

internal class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
}

Or you can just pass nothing like this:

internal class AppDbContext : DbContext
{
    public AppDbContext() : base()
    {
    }
}

In both cases you have the context registered like this, without options:

services..AddDbContext<AppDbContext>()

This has some differences though. In the case where you don't pass the options, logging does not work. This is because when EFCore creates the ScopedLoggerFactory it needs the application service provider to have the application ILoggerFactory, which you only have when injecting the options via DI. So what it does is creating a new LoggerFactory() which does not log anything.

return new ScopedLoggerFactory(new LoggerFactory(), dispose: true);

I think we expect both cases to have the same behavior. One solution can be removing the parameterless DbContext constructor, but I don't know if that's feasible.

@ajcvickers
Copy link
Member

@michaeltg17 EF is intended to be used from a D.I. container, in which case services from D.I. are passed to EF via the DbContextOptions parameter on the DbContext constructor. EF is also intended to be used without D.I., in which case the parameterless constructor can be used. In this case, there is no place to obtain D.I. services, such as a logging provider, and so these services are not available. They can be registered manually, if desired.

So, there is no way for these two constructors to perform the same way, and indeed, it is by-design that they do not.

@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale May 1, 2024
@ajcvickers ajcvickers removed their assignment May 1, 2024
@ajcvickers ajcvickers added closed-no-further-action The issue is closed and no further action is planned. and removed type-bug area-logging labels May 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-no-further-action The issue is closed and no further action is planned. customer-reported
Projects
None yet
Development

No branches or pull requests

3 participants