title: Disposable singleton in C#
body: <p>I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?</p>
  
  <p>The interface I would like is something like:</p>
  
  <pre><code>var x = Foo.Instance;
  var y = Foo.Instance; // x == y
  ...
  x.Release(); // this causes the next Foo.Instance to return a fresh object
               // also, it assumes no further operations on x/y will be performed.
  </code></pre>
  
  <p>Note - the pattern has to be thread-safe, of course.</p>
  
  <p><strong>Edit</strong> - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.</p>
  
  <p>I would also prefer a pattern that can be reused, if possible.</p>