In an MVC / WebAPI environment I would use InRequestScope
to bind the DbContext
.
However, I am now on a Console application / Windows service / Azure worker role (doesn't really matter, just there's no Web request scope), which periodically creates a number of Tasks
that run asynchronously. I would like each task to have its own DbContext
, and since tasks run on their own thread, I tried binding DbContext
using InThreadScope
.
Unfortunately, I realize that the DbContext is not disposed when a task is finished. What actually happens is, the thread returns to the Thread Pool and when it is assigned a new task, it already has a DbContext, so DbContexts stay alive forever.
Is there a way InThreadScope
can be used here or should I use some other scope? How can ThreadScope be used when threads are returning from ThreadPool every now and then?
InNamedScope
). But that is not future proof for example when you want to create DbContext outside of a task or when you want to have multiple (sequential) DbContext inside a single task,... etc – InlyDbContext
in a thread-local so we don't need method-injection. This works perfectly for us (as described here: #21675090). – Inly