Ninject - 当RequestScope无意义时,DbContext应在什么范围内绑定?

zaf*_*s.m 13 multithreading entity-framework dependency-injection ninject threadpool

在MVC/WebAPI环境中,我将用于InRequestScope绑定DbContext.

但是,我现在处于Console应用程序/ Windows服务/ Azure辅助角色(并不重要,只是没有Web请求范围),它会定期创建一些Tasks异步运行.我希望每个任务都有自己的DbContext,并且由于任务在自己的线程上运行,我尝试DbContext使用绑定InThreadScope.

不幸的是,我意识到任务完成时不会处理DbContext.实际发生的是,线程返回线程池,当它被分配一个新任务时,它已经有一个DbContext,所以DbContexts永远保持活着.

有没有办法InThreadScope在这里使用或我应该使用其他范围?当线程从ThreadPool中不时返回时,如何使用ThreadScope?

Jan*_*sky 2

如果您决定继续使用自定义范围,解决方案是:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

捆绑:

Bind<DbContext>().To<MyDbContext>().InScope(c => CurrentScope.Instance)
Run Code Online (Sandbox Code Playgroud)

最后:

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
}
Run Code Online (Sandbox Code Playgroud)