Hi @Kmcnet Thanks for sharing your concern with us. Regarding your question tough our official document clear instruction for your scenario however, I am trying to explain it as per your scenario.
In genral ApplicationDbContext
can be used in ASP.NET Core controllers
or other services
through constructor injection
Like below:
public class HomeController
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
}
Note: Once you initiate the _context
globally then it can be used in Controller Action
level. Now let's consider your below scenario:
Question: My controller may need to make more than one method call where each method requires the context. How should this be handled?
As you might know Entity Framework Core does not support multiple parallel operations being run on the same DbContext
instance. In that case, if you only need to call the method one after another then async
, await
can resolve your issue. However, if you want to call them concurrently
then this way won't work for you and it will throw InvalidOperationException
Handle Parallel Method Operation:
Using dependency injection
, this can be achieved by either registering
the context as scoped
, and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext
. For example
public class EFDenpendencyHostedService : IHostedService
{
private readonly IServiceScopeFactory scopeFactory;
public EFDenpendencyHostedService(IServiceScopeFactory scopeFactory)
{
this.scopeFactory = scopeFactory;
}
public void ExecuteDbContext()
{
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();
…
}
}
…
}
Note: Once you have created the middleware hosted service
then register it in the startup.cs/ program.cs class
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Md Farid Uddin Kiron