使用IoC时如何管理对象处置? [英] How do I manage object disposal when I use IoC?

查看:209
本文介绍了使用IoC时如何管理对象处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是Ninject 2.

My case it is Ninject 2.

// normal explicit dispose
using (var dc = new EFContext) 
{
}

但是有时候我需要保持上下文更长的时间或在函数调用之间. 所以我想通过IoC范围来控制这种行为.

But sometimes I need to keep the context longer or between function calls. So I want to control this behavior through IoC scope.

// if i use this way. how do i make sure object is disposed.
var dc = ninject.Get<IContext>() 

// i cannot use this since the scope can change to singleton. right ??
using (var dc = ninject.Get<IContext>()) 
{
}

样本范围

Container.Bind<IContext>().To<EFContext>().InSingletonScope();
// OR
Container.Bind<IContext>().To<EFContext>().InRequestScope();

推荐答案

据我所知(大约一个月前我进行了一项研究),Ninject根本不支持生命周期管理. Castle Windsor和AutoFac(在某种程度上还可以使用StructureMap,但仅当使用嵌套容器时)将负责处理它们在适当时候创建的一次性组件.

From what I know (I did a research about a month ago) Ninject does not support lifecycle management at all. Castle Windsor and AutoFac (and to some extent StructureMap, but only when using nested containers) will take care of disposing disposable components they create at appropriate time.

这篇关于使用IoC时如何管理对象处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆