Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid repetitive coding when disposing of objects

With a purpose of memory optimization we've been adding these lines of code:

public class Whatever: IDisposable

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
    if (!this.disposed)
    {
        if (disposing)
        {
            context.Dispose();
        }
    }
    this.disposed = true;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

To every single of our repositories, then are updating tests for each repo as well. I am wondering, since copy+paste isn't really encouraged in coding isn't there a better way to implement this? Especially annoying since, depending on a project, we have 10-40 repositories...

like image 964
Emilija Vilija Trečiokaitė Avatar asked Aug 13 '26 14:08

Emilija Vilija Trečiokaitė


1 Answers

Perhaps simpler - use the context itself to track disposal:

protected virtual void Dispose(bool disposing)
{
    if (disposing) context?.Dispose();
    context = null;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

Note that I also think it is vanishingly unlikely that you have a finalizer involved here (and if you do, that is probably a big mistake), so honestly: you can simplify further:

public void Dispose()
{
    context?.Dispose();
    context = null;
}
like image 167
Marc Gravell Avatar answered Aug 15 '26 04:08

Marc Gravell