using System; namespace Unosquare.Swan.Abstractions { /// /// 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 Boolean _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() => this.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(Boolean disposeManaged) { if(this._isDisposing) { return; } this._isDisposing = true; // free managed resources if(LazyInstance == null) { return; } try { IDisposable disposableInstance = LazyInstance.Value as IDisposable; disposableInstance?.Dispose(); } catch { // swallow } } } }