Search code examples
c#entity-framework-coreblazor-server-sideasp.net-core-identityef-core-7.0

Blazor Server + EF Core 7 + Idenitty --> using a custom DbContext and DbContextFactory


The question is simple: how can I make my own context using the identity. I don't want to use the default ApplicationDbContext.

In Program.cs by default you have:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

When I change that to use

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
void BuildOptions(DbContextOptionsBuilder options) => options.UseSqlServer(connectionString).EnableSensitiveDataLogging(); // todo: not for production

builder.Services.AddDbContext<OpmContext>(BuildOptions);
builder.Services.AddDbContextFactory<OpmContext>(BuildOptions);

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<OpmContext>();

and change my own DbContext to inherit from IdentityContext:

public class OpmContext : IdentityDbContext 
{
    public OpmContext(DbContextOptions<OpmContext> options) : base(options)
    {
    }
}

I get:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory`1[Foo.Bar.Data.OpmContext] Lifetime: Singleton

I had a look at Using Identity with AddDbContextFactory in Blazor but can't seem to get it working. Any suggestions?

The goal is to inject and use IDbContextFactory<OpmContext> DbFactory in razor pages or own services.


Solution

  • Change the order:

    builder.Services.AddDbContextFactory<OpmContext>(options =>
        options.UseSqlServer(connectionString));
    
    builder.Services
        .AddDbContext<OpmContext>(options =>
            options.UseSqlServer(connectionString));
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();
    
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<OpmContext>();