using System;
namespace Swan
{
///
/// Represents a singleton pattern abstract class.
///
/// The type of class.
public abstract class SingletonBase : IDisposable
where T : class
{
///
/// The static, singleton instance reference.
///
protected static readonly Lazy LazyInstance = new Lazy(
valueFactory: () => Activator.CreateInstance(typeof(T), true) as T,
isThreadSafe: true);
private bool _isDisposing; // To detect redundant calls
///
/// Gets the instance that this singleton represents.
/// If the instance is null, it is constructed and assigned when this member is accessed.
///
///
/// The instance.
///
public static T Instance => LazyInstance.Value;
///
public void Dispose() => Dispose(true);
///
/// Releases unmanaged and - optionally - managed resources.
/// Call the GC.SuppressFinalize if you override this method and use
/// a non-default class finalizer (destructor).
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
protected virtual void Dispose(bool disposeManaged)
{
if (_isDisposing) return;
_isDisposing = true;
// free managed resources
if (LazyInstance == null) return;
try
{
var disposableInstance = LazyInstance.Value as IDisposable;
disposableInstance?.Dispose();
}
catch
{
// swallow
}
}
}
}