问题描述
在MVC/WebAPI环境中,我将使用InRequestScope
绑定DbContext
.
In an MVC / WebAPI environment I would use InRequestScope
to bind the DbContext
.
但是,我现在是在控制台应用程序/Windows服务/Azure工作角色上(这并不重要,只是没有Web请求作用域),它会定期创建许多异步运行的Tasks
.我希望每个任务都有自己的DbContext
,并且由于任务在各自的线程上运行,因此我尝试使用InThreadScope
绑定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
.
不幸的是,我意识到在完成任务时不会释放DbContext.实际发生的情况是,线程返回到线程池,并且在为其分配了新任务时,它已经具有一个DbContext,因此DbContext可以永远保持活动状态.
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.
这里是否可以使用InThreadScope
的方式,还是应该使用其他范围?当线程不时从ThreadPool返回时,如何使用ThreadScope?
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?
推荐答案
如果您决定继续使用自定义范围,则解决方案是:
If you decide to go on with custom scope, the solution is:
public sealed class CurrentScope : INotifyWhenDisposed
{
[ThreadStatic]
private static CurrentScope currentScope;
private CurrentScope()
{
}
public static CurrentScope Instance => currentScope ?? (currentScope = new CurrentScope());
public bool IsDisposed { get; private set; }
public event EventHandler Disposed;
public void Dispose()
{
this.IsDisposed = true;
currentScope = null;
if (this.Disposed != null)
{
this.Disposed(this, EventArgs.Empty);
}
}
}
绑定:
Bind<DbContext>().To<MyDbContext>().InScope(c => CurrentScope.Instance)
最后:
using (CurrentScope.Instance)
{
// your request...
// you'll get always the same DbContext inside of this using block
// DbContext will be disposed after going out of scope of this using block
}
这篇关于Ninject-当RequestScope无意义时,DbContext应该绑定在哪个范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!