IDisposable Pattern (in UnitOfWork)

Wed, 16 Oct 2019 11:06 UTC by garethbrown

Updated 2021/02/19


  // Reference: https://stackoverflow.com/questions/151051/when-should-i-use-gc-suppressfinalize

  using System;

  namespace Example.Prototype.Db
  {
      public class UnitOfWork : IDisposable
      {
          private bool _disposed;

          // ..

          public void Dispose()
          {
              Dispose(true);
              
              // Use SupressFinalize in case a subclass
              // of this type implements a finalizer.

              GC.SuppressFinalize(this);
          }

          /// <summary>
          /// Implements dispose logic
          /// </summary>
          /// <param name="disposing">Should be true if Dispose is being called by the finalizer versus the IDisposable.Dispose() implementation.</param>
          private void Dispose(bool disposing)
          {
              if (!_disposed)
              {
                  if (disposing)
                  {
                      try
                      {
                          if (DbConnection != null)
                          {
                              if (DbConnection.State != ConnectionState.Closed)
                              {
                                  DbConnection.Close();
                              }
                          }
                      }
                      finally
                      {
                          DbConnection?.Dispose();
                      }
                  }
  
                  // Indicate that the instance has been disposed.
  
                  _disposed = true;
              }
          }
      }
  }

The information on this site is provided “AS IS” and without warranties of any kind either
express or implied. To the fullest extent permissible pursuant to applicable laws, the author disclaims all warranties, express or implied, including, but not limited to, implied warranties of merchantability, non-infringement and suitability for a particular purpose.

UI block loader
One moment please ...