Inspiration
Inspiration

Reputation: 83

Asp net core identity: how to get default ApplicationDbContext outside controller?

I use Net Core 2.1 and I need to do some preparations on startup which require several direct Identity database queries.

I tried:

using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>()
                    .CreateScope())
{
    var identityDb = serviceProvider.GetService<ApplicationDbContext>();
}

these lines produce exception: Cannot resolve scoped service 'Ecoc.Data.ApplicationDbContext' from root provider. Is there a way to get database context in arbitrary place of code?

Upvotes: 0

Views: 190

Answers (2)

blow
blow

Reputation: 13209

Use IServiceScopeFactory instead of IServiceProvider and then create a scope and use its ServiceProvider.

Related to you example:

var identityDb = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();

Upvotes: 1

Inspiration
Inspiration

Reputation: 83

Found the correct approach here (they access Session from arbitrary class as example) https://neelbhatt.com/2018/02/10/implement-session-in-net-core2-0/

Upvotes: 0

Related Questions