0

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?

2 Answers 2

1

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

Related to you example:

var identityDb = serviceScope.ServiceProvider.GetService<ApplicationDbContext>(); 
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.