使用IoC时如何管理对象处理?

Ava*_*val 5 dependency-injection ninject ioc-container inversion-of-control

我的情况是Ninject 2.

// normal explicit dispose
using (var dc = new EFContext) 
{
}
Run Code Online (Sandbox Code Playgroud)

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

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

示例范围

Container.Bind<IContext>().To<EFContext>().InSingletonScope();
// OR
Container.Bind<IContext>().To<EFContext>().InRequestScope();
Run Code Online (Sandbox Code Playgroud)

Krz*_*mic 3

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