DbContext for background tasks via Dependency Injection

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)