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...
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With