Ninject - In what scope DbContext should get binded when RequestScope is meaningless?

后端 未结 1 1620
无人及你
无人及你 2021-01-04 06:13

In an MVC / WebAPI environment I would use InRequestScope to bind the DbContext.

However, I am now on a Console application / Windows servi

1条回答
  •  一整个雨季
    2021-01-04 06:56

    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);
            }
        }
    }
    

    Binding:

    Bind().To().InScope(c => CurrentScope.Instance)
    

    And finally:

    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
    }
    

    0 讨论(0)
提交回复
热议问题