How to access injected services in partial DbContext OnConfiguring?
06:42 22 Sep 2023

When scaffolding a DbContext with dotnet ef dbcontext scaffold, the tool generates a partial class. I then create another partial implementation of the DbContext to implement OnConfiguring (need to pass --no-onconfiguring).

However, now I want to access a service from DI inside the OnConfiguring method, namely IHttpContextAccessor.

What I would do when using a code first approach (without the partial classes) is inject the IHttpContextAccessor in the constructor of the DbContext, store it in a private readonly field and use it in the OnConfiguring method.

This seemingly also works with the partial DbContext. I only had to make the field nullable because the empty constructor generated by the scaffolding didn't assign it, giving a warning.

My full implementation looks like this:

// Partial DbContext generated by scaffolding
public partial class MyContext : DbContext
{
    public MyContext(DbContextOptions options)
        : base(options)
    {
    }

    // Rest of the scaffolded context ...
}

// My partial DbContext
public partial class MyContext : DbContext
{
    private readonly IHttpContextAccessor? _httpContextAccessor;

    public MyContext(
        DbContextOptions options,
        IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Use HttpContext to determine connection string
    }
}

My question is simply if this is the correct way to go about this? I'm confused as to how DI chooses the right constructor in this case.

I also saw that DbContext has a method named GetService but when I tried using it in OnConfiguring, I got an exception saying the context is not fully configured yet.

Thanks in advance.

c# asp.net-core dependency-injection entity-framework-core