Ninject and DataContext disposal

后端 未结 3 1794
南旧
南旧 2021-02-18 14:44

I\'m using Ninject to retrieve my DataContext from the kernel and I was wondering if Ninject automatically disposes the DataContext, or how he handles the dispose() behaviour. F

3条回答
  •  后悔当初
    2021-02-18 14:57

    In addition to the standard scopes of Transient, OnePerThread, and Singleton, you can use an ActivationBlock in order to control the lifetime of a whole set of objects. When the block is disposed, all object retrieved by the block go out of scope - so singletons and others are disposed of when their instances are requested by the activation block.

    var kernel = new StandardKernel();
    kernel.Bind().ToSelf();
    
    NotifiesWhenDisposed instance = null;
    using(var block = new ActivationBlock(kernel))
    {
        instance = block.Get();
        instance.IsDisposed.ShouldBeFalse();
    }
    
    instance.IsDisposed.ShouldBeTrue();
    

提交回复
热议问题