Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

asp.net core - DbContext for background tasks via Dependency Injection

I am probably not thinking in the right direction. I am fairly new to Dependency Injection and ASP.Net Core.

I have an ASP.Net core website, and one of the tasks is to import data from an excel sheet to a database that a user will upload. The excel sheets can be huge and the data transformation tasks are time-taking, hence I wish to perform them in the background. i.e. The user will upload the sheet, the response will be sent immediately and the background job/thread will import the data.

I am trying to run the background job by:

Task.Run(() => ProcessImport(model));

The problem I run into is that the Process import method calls Services that have repository classes accessing the AppDbContext via ASP.Net Dependency Injection Container that is added as Scoped and once the response is sent back, the context is disposed of. I am getting a runtime exception that you cannot use a context after it's disposed of.

My question is, what is the best way to handle this situation? Should I make the AppDbContext singleton? Should I create a new instance of AppDbContext in the ProcessImport method, and pass it along? I have read DbContext is not thread-safe, so is that a good approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...