C# Do I use dispose() correctly?
For example. We have CatDataStore
class who works with data base and implements IDisposable
. This is full implements IDisposable
:
class CatDataStore : IDisposable
{
//data context contains models, connection string... etc
private ApplicationDbContext _context = new ApplicationDbContext();
private bool disposed;
public async Task<bool> AddItem(Cat item)
{
await _context.Cats.AddAsync(item);
await _context.SaveChangesAsync();
return true;
}
//smth CRUD methods..
public void Dispose()
{
Dispose(true);
//GC can't eat this
GC.SupressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (disposed)
throw new ObjectDisposedException();
_context.Dispose();
}
disposed = true;
}
~CatDataStore() => Dispose(false);
}