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 u
You could use a nested lazy singleton (See here) with some simple modifications:
public sealed class Singleton : IDisposable
{
Singleton()
{
}
public static Singleton Instance
{
get
{
if (!Nested.released)
return Nested.instance;
else
throw new ObjectDisposedException();
}
}
public void Dispose()
{
disposed = true;
// Do release stuff here
}
private bool disposed = false;
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Remember to throw ObjectDisposedException in all public methods/properties of the object if it has been disposed.
You should also, provide a finalizer method for the object, in case Dispose doesn't get called. See how to correctly implement IDisposable here.