Ninject and DataContext disposal

。_饼干妹妹 提交于 2019-12-03 22:20:38

I am investigating this for my colleague Bas. I was looking in the Ninject 2 source code (http://github.com/ninject/ninject.git), and there seems to be some life cycle management.

When there's an other scope than transient, then the garbage collection of that scope will trigger the deactivation (through the pipeline) of all instances linked to that scope. On deactivation one of the default strategies is DisposableStrategy, this strategy will dispose the instance if it's IDisposable!

I saw a lot of answers on stackoveflow that Ninject doesn't do any life cycle management, maybe this was true for a previous version of Ninject?

But this behaviour is quite tricky, since when using injected services you are not aware of the scope. Because of that you don't know if you have to dispose the object yourself (transient) or that Ninject will take care of this.

Changes to the scope of a service could therefor introduce bugs.

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<NotifiesWhenDisposed>().ToSelf();

NotifiesWhenDisposed instance = null;
using(var block = new ActivationBlock(kernel))
{
    instance = block.Get<NotifiesWhenDisposed>();
    instance.IsDisposed.ShouldBeFalse();
}

instance.IsDisposed.ShouldBeTrue();
Igor Zevaka

Doesn't look like ninject has any sort of lifetime management. This question sheds more light on it.

Perhaps you can investigate implementing your own behaviour like shown in this blog. I haven't tried it but maybe you can make something along the lines of per request singleton with the older instance being disposed when the new one is created.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!