使用 IoC 时如何管理对象处置?
我的例子是 Ninject 2。
// normal explicit dispose
using (var dc = new EFContext)
{
}
但有时我需要在函数调用之间保持更长时间的上下文。 所以我想通过 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>())
{
}
样本范围
Container.Bind<IContext>().To<EFContext>().InSingletonScope();
// OR
Container.Bind<IContext>().To<EFContext>().InRequestScope();
My case it is Ninject 2.
// normal explicit dispose
using (var dc = new EFContext)
{
}
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>())
{
}
Sample scopes
Container.Bind<IContext>().To<EFContext>().InSingletonScope();
// OR
Container.Bind<IContext>().To<EFContext>().InRequestScope();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知(大约一个月前我做了一项研究)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.
如果您可以控制
IContext
的接口,请将IDisposable
添加到它继承的接口列表中。如果没有,则将您获得的IContext
向下转换为 IDisposable...您还可以选择更改
IContext
的接口,以通过组合来完成此操作,如果您控制IContext
...If you have control over the interface of
IContext
, addIDisposable
to the list of interfaces from which it inherits. If not, downcast theIContext
you get to an IDisposable...You also have the option of altering the interface of
IContext
to do this by composition, if you controlIContext
...除了 Transient、OnePerThread 和 Singleton 的标准范围之外,您还可以使用 ActivationBlock 来控制整个对象集的生命周期。当块被释放时,块检索的所有对象都会超出范围 - 因此当激活块请求其实例时,单例和其他对象将被释放。
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.