通过依赖注入实现后台任务的 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 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));

我遇到的问题是 Process 导入方法调用服务,这些服务具有通过 ASP.Net 依赖注入容器访问 AppDbContext 的存储库类,该容器被添加为 Scoped,并且一旦发送回响应,上下文就会被处理掉.我收到一个运行时异常,您在处理完上下文后无法使用它.

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.

我的问题是,处理这种情况的最佳方法是什么?我应该使 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).

参见 this 例如.我用这个库运行小而快的任务.

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天全站免登陆