通过依赖注入的后台任务的DbContext [英] DbContext for background tasks via Dependency Injection

本文介绍了通过依赖注入的后台任务的DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能没有考虑正确的方向.我对依赖注入和ASP.Net Core还是陌生的.

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

我有一个ASP.Net核心网站,任务之一是将数据从excel工作表导入到用户要上传的数据库中. Excel工作表可能非常庞大,并且数据转换任务非常耗时,因此我希望在后台执行它们.即,用户将上传工作表,响应将立即发送,后台作业/线程将导入数据.

I have a 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));

我遇到的问题是Process导入方法调用服务,这些服务的存储库类通过ASP.Net依赖注入容器(作为作用域添加)访问AppDbContext,一旦将响应发送回去,则处理上下文.我收到了一个运行时异常,即您不能在处理完上下文后再使用它.

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. I am getting a runtime exception that you cannot use a context after its disposed.

我的问题是,处理这种情况的最佳方法是什么?我应该使AppDbContext单身吗?我应该在ProcessImport方法中创建AppDbContext的新实例,然后将其传递吗?我已经读过DbContext不是线程安全的,那是一种好方法吗?

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?

推荐答案

您应将IServiceScopeFactory实例(单例)传递到任务中.

You should pass IServiceScopeFactory instance (it's singleton) into your task.

内部任务中,当数据到达时,您应该创建新的CreateScope()并从该范围请求服务.数据处理完成后,请处置此范围(但保留对IServiceScopeFactory的引用以进行下一次运行).

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.

如Gert所写,对于繁重/长时间运行的任务,请不要依赖于您的任务将始终运行到完成.准备重新启动,准备重新处理相同的数据.

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.

这篇关于通过依赖注入的后台任务的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆