I am probably not thinking in the right direction. I am fairly new to Dependency Injection and ASP.Net Core.
I have a ASP.Net core website, and one of the tasks is t
To breakdown your questions:
what is the best way to handle this situation?
It's not ideal for the API to handle the long-running tasks. You can delegate the process to a background application
Should I make the AppDbContext singleton?
The dbContext should not be singleton in a web application scenario as it can pose problems like managing transactions.
what is the best way to handle this situation?
breakdown the various services/process:
Should I create a new instance of AppDbContext in the ProcessImport method, and pass it along?
Since it is not thread-safe, create and use a separate instance of your dbContext class in each thread.
I have read DbContext is not thread safe, so is that a good approach?
For an in-depth guide of using EF dbContext, checkout this blog: http://mehdi.me/ambient-dbcontext-in-ef6/
You should pass IServiceScopeFactory
instance (it's singleton) into your task.
Inside task, when data arrives, you should create new CreateScope()
and request services from that scope. When data process finishes - dispose this scope (but hold reference to IServiceScopeFactory
for next run).
See this for example. I run small and fast tasks with this library.
For heavy / long running tasks, as Gert wrote, don't rely that your task will always run to completion. Be ready for restart, be ready for re-processing of the same data.