导出LifetimeContext
为什么 ExportLifetimeContext
存在?它是做什么用的?为什么有必要对该对象调用 Dispose?我真的需要费心打电话吗?如果我必须花时间思考资源管理,那感觉就不太受管理,对我来说感觉不太受管理。
此处置是否与 Value 属性相关?仅使用 CreateExport().Value
是否存在特定问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您要求 ExportFactory 创建新对象时,MEF 实际上还可能创建依赖项以及这些依赖项的依赖项,等等。由于您请求单个对象,可能会创建许多对象。
其中一些额外的对象可能是
IDisposable
,容器负责在不再需要它们时处置它们。要向容器发出您已完成对象使用的信号,请调用
ExportLifetimeContext.Dispose()
。然后,如有必要,MEF 容器将负责处理所请求的对象及其依赖项。如果您不这样做,MEF 将永远保留对这些对象的引用,等待可以处置它们的信号。在 Autofac 2 中,存在非常相似的机制。它们使用
Func>
而不是ExportFactory
,并且您需要调用Owned.Dispose()
进行清理向上。edit: The MEF documentation has a Parts lifetime section where it is described in which cases exactly the container keeps references to exports. It does not yet mention
ExportLifetimeContext.Dispose
but I imagine this is similar toCompositionContainer.ReleaseExport
.edit: note that
ExportFactory
is intended for cases where you have a clearly defined lifetime. If this is not the case (or you know that clean-up is never necessary), then you should create your own factory implementation. Of course, it is then your responsibility to make sure that nothingIDisposable
is created, since it would be impossible to clean it up properly.以下是使用
Func
自定义工厂导入/导出的示例。When you ask an
ExportFactory
to create a new object, MEF might actually also create dependencies, and the dependencies of those dependencies, etcetera. Many objects might be created because you asked for a single object.Some of these extra objects might be
IDisposable
, and the container is responsible for disposing those when they are no longer necessary.To signal to the container that you are done using your object, you call
ExportLifetimeContext<T>.Dispose()
. The MEF container will then take care of disposing the requested object and its dependencies if necessary. If you don't do this, MEF will keep references to these objects forever, waiting for a signal that it can dispose them.In Autofac 2, a very similar mechanism exists. Instead of
ExportFactory
, they useFunc<Owned<T>>
and you need to callOwned<T>.Dispose()
to clean up.edit: The MEF documentation has a Parts lifetime section where it is described in which cases exactly the container keeps references to exports. It does not yet mention
ExportLifetimeContext.Dispose
but I imagine this is similar toCompositionContainer.ReleaseExport
.edit: note that
ExportFactory
is intended for cases where you have a clearly defined lifetime. If this is not the case (or you know that clean-up is never necessary), then you should create your own factory implementation. Of course, it is then your responsibility to make sure that nothingIDisposable
is created, since it would be impossible to clean it up properly.Here is an example of a custom factory import/export using
Func<T>
.