1

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.

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
juFo
  • 17,849
  • 10
  • 105
  • 142
  • Your issue seems like this one [Use both AddDbContextFactory() and AddDbContext() extension methods in the same project](https://stackoverflow.com/questions/65022729/use-both-adddbcontextfactory-and-adddbcontext-extension-methods-in-the-same). Try to remove the AddDbContext. If you really need one register it as singleton. – Roberto Ferraris Feb 17 '23 at 07:29

1 Answers1

2

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>();
Rena
  • 30,832
  • 6
  • 37
  • 72