处理所有实现IDisposable的嵌套对象

Luc*_*ike 4 .net c# entity-framework

我的项目中有以下代码.我是否必须明确处理内部类?如果是这样的话?

public class Outer : IDisposable
{
    Context context = new Context();
    Inner inner;

    public Outer()
    {
        inner = new Inner(context);
    }

    public void Dispose()
    {
        context.Dispose();
    }
}

public class Inner : IDisposable
{
    Context context;

    public Inner(Context context)
    {
        this.context = context;
    }

    public void Dispose()
    {
        context.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

Context类似于Entity Framework中的DbContext.

Jon*_*eet 6

那么,在这种情况下,你需要找出实际应该"拥有"上下文的内容.如果你有它Inner,你真的需要它Outer吗?他们中哪一个真的对他们负责?它看起来像你真的想要:

public sealed class Outer : IDisposable
{
    private readonly Inner inner;

    public Outer()
    {
        inner = new Inner(new Context());
    }

    public void Dispose()
    {
        inner.Dispose();
    }
}

public sealed class Inner : IDisposable
{
    private readonly Context context;

    public Inner(Context context)
    {
        this.context = context;
    }

    public void Dispose()
    {
        context.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,已经制作OuterInner密封,不需要编写受保护的Dispose(bool disposing)方法等 - 这实际上是为了继承,这一般会变得很痛苦.如果您确实需要子类Outer并且Inner可能需要处理更多资源,那么您将需要更复杂的实现.

就个人而言,如果可能的话,我尽量实现IDisposable,并且只在带有using语句的局部变量中保留一次性事物.当然,这并不总是可行,但值得尝试......