DbContext for background tasks via Dependency Injection

前端 未结 2 1973
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:30

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

2条回答
  •  眼角桃花
    2020-12-08 01:47

    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.

提交回复
热议问题