2009 Advent Calendar December 6th

Since I want the transaction we're creating to take the lock when created I also want to release the lock when the transaction is disposed:

    1:      public class When_using_a_transaction
   2:      {
   3:          class FakeLock : Lock
   4:          {
   5:              public bool IsLocked { get; private set; }
   6:   
   7:              public FakeLock()
   8:              {
   9:                  IsLocked = false;
  10:              }
  11:   
  12:              public void Lock()
  13:              {
  14:                  IsLocked = true;
  15:              }
  16:   
  17:              public void Unlock()
  18:              {
  19:                  IsLocked = false;
  20:              }
  21:          }
  22:   
  23:          private FakeLock _lock;
  24:   
  25:          public When_using_a_transaction()
  26:          {
  27:              _lock = new FakeLock();
  28:          }
  29:   
  30:          [Fact]
  31:          void It_should_take_lock_when_created()
  32:          {
  33:              Assert.False(_lock.IsLocked);
  34:              using (Transaction transaction = new Transaction(_lock))
  35:              {
  36:                  Assert.True(_lock.IsLocked);
  37:              }
  38:          }
  39:   
  40:          [Fact]
  41:          void It_should_release_lock_when_leaving_scope()
  42:          {
  43:              using (Transaction transaction = new Transaction(_lock))
  44:              {
  45:                  Assert.True(_lock.IsLocked);
  46:              }
  47:              Assert.False(_lock.IsLocked);
  48:          }
  49:      }

And the transaction implementation:

    1:      public class Transaction : IDisposable
   2:      {
   3:          private readonly Lock _lock;
   4:   
   5:          public Transaction()
   6:              : this(new MutexLock())
   7:          {
   8:   
   9:          }
  10:   
  11:          public Transaction(Lock aLock)
  12:          {
  13:              _lock = aLock;
  14:              _lock.Lock();
  15:          }
  16:   
  17:          public void Dispose()
  18:          {
  19:              _lock.Unlock();
  20:          }
  21:      }