class Usingifier<T> : IDisposable where T : class
{
private readonly Func<T> _initialize;
private readonly Action<T> _cleanUp;
private bool _disposed;
private T _state;
public Usingifier(Func<T> initialize, Action<T> cleanUp)
{
_initialize = initialize;
_cleanUp = cleanUp;
}
public Usingifier<T> Initialize()
{
_state = _initialize();
_disposed = false;
return this;
}
public virtual void Dispose()
{
if (_disposed)
{
throw new ObjectDisposedException(null, "Object has been cleaned up.");return;
}
_disposed = true;
if (_state != null)
{
_cleanUp(_state);
}
}
}
class Usingifier<T> : IDisposable where T : class
{
private readonly Func<T> _initialize;
private readonly Action<T> _cleanUp;
private readonly bool _autoDispose;
private bool _disposed;
private T _state;
public Usingifier(Func<T> initialize, Action<T> cleanUp, bool autoDispose = false)
{
_initialize = initialize;
_cleanUp = cleanUp;
_autoDispose = autoDispose;
}
public Usingifier<T> Initialize()
{
_state = _initialize();
_disposed = false;
return this;
}
public virtual void Dispose()
{
if (_disposed)
{
throw new ObjectDisposedException(null, "Object has been cleaned up.");return;
}
_disposed = true;
if (_state != null)
{
_cleanUp(_state);
}
if (_autoDispose && _state is IDisposable disposable)
{
disposable.Dispose();
}
}
interface IUsingifier<T> : IDisposable where T : class
{
T State { get; }
Usingifier<T> Initialize();
}
class Usingifier<T> : IUsingifier<T> where T : class
{
private readonly Func<T> _initialize;
private readonly Action<T> _cleanUp;
private readonly bool _autoDispose;
private bool _disposed;
public Usingifier(Func<T> initialize, Action<T> cleanUp, bool autoDispose = false)
{
_initialize = initialize;
_cleanUp = cleanUp;
_autoDispose = autoDispose;
}
public T State { get; private set; }
public Usingifier<T> Initialize()
{
State = _initialize();
_disposed = false;
return this;
}
public virtual void Dispose()
{
if (_disposed)
{
throw new ObjectDisposedException(null, "Object has been cleaned up.");return;
}
_disposed = true;
if (State != null)
{
_cleanUp(State);
}
if (_autoDispose && State is IDisposable disposable)
{
disposable.Dispose();
}
}
}