编程语言
首页 > 编程语言> > c#-MEF和对象处置

c#-MEF和对象处置

作者:互联网

当我创建一个对象并将其添加到容器中,然后完成操作后,如何确保正确处理该对象?

http://msdn.microsoft.com/en-us/library/ee155691(v=vs.110).aspx

For long-lived composition containers, memory consumption by parts
with a creation policy of non-shared can become a problem. These
non-shared parts can be created multiple times and will not be
disposed until the container itself is disposed. To deal with this,
the container provides the ReleaseExport method. Calling this method
on a non-shared export removes that export from the composition
container and disposes it. Parts that are used only by the removed
export, and so on down the tree, are also removed and disposed. In
this way, resources can be reclaimed without disposing the composition
container itself.

因此,例如,如果我在MEF中使用Caliburn.micro之类的东西并创建一个新的ViewModel,则当ViewModel关闭时,如果我在容器上添加ReleaseExport调用,此操作是否会清理引用,使其不再占用内存? (这是正确的方法吗?)

另外,调用ReleaseExport会阻止我将来创建该类型的另一个对象,还是目录仍然包含该项目,并且我可以随时重新创建它?

解决方法:

MEF允许两种类型的导出-共享和非共享.

共享出口就像单身人士-每个消费者共享同一实例.这些共享实例由MEF直接管理.当您在MEF容器上调用Dispose()时,它将自动按照相反的导入顺序释放这些对象.

非共享资源更加复杂.由于存在多个实例,因此MEF无法保证发布的正确顺序.在这种情况下,您应遵循与调用Dispose()时所使用的指导相同的指导,以确定何时释放导入的对象.

每个非共享的MEF导入对象都应拥有一个负责其生命周期的所有者-通常是首先导入该对象的父对象.一旦父对象确保没有人使用此导入的对象,它将在其上调用ReleaseExport.典型的模式是在所有者对象的Dispose()中释放导入的对象.

class OwnerClass : IDisposable
{
    [Import(RequiredCreationPolicy=CreationPolicy.NonShared)]
    private ConsumedClass myInstance;

    [Import(RequiredCreationPolicy=CreationPolicy.Shared)]
    private CompositionContainer container;

    // Do stuff

    public void Dispose()
    {
        container.ReleaseExport(myInstance);
    {
}

调用ReleaseExport会从容器中释放该特定实例.定义保留在目录中.因此,您仍然应该能够创建更多实例.这是一个很好的讨论:

https://mef.codeplex.com/discussions/228535

The job of ReleaseExport is to cleanup a particular export and it’s
dependencies from the container early, meaning before disposing of the
container itself which will cleanup and dispose all objects
constructed by the container. Now calling ReleaseExport will do
different things depending on the particular export, for example for a
Shared export it will actually do nothing but for a NonShared export
it will release it and walk its dependency graph releasing them but
again it will stop and do nothing for any dependencies that are Shared
exports.

标签:mef,c,caliburn-micro
来源: https://codeday.me/bug/20191029/1962080.html