using System;
namespace Umbraco.Core.Scoping
{
///
/// Provides a base class for scope contextual objects.
///
///
/// A scope contextual object is enlisted in the current scope context,
/// if any, and released when the context exists. It must be used in a 'using'
/// block, and will be released when disposed, if not part of a scope.
///
public abstract class ScopeContextualBase : IDisposable
{
private bool _scoped;
///
/// Gets a contextual object.
///
/// The type of the object.
/// A scope provider.
/// A context key for the object.
/// A function producing the contextual object.
/// The contextual object.
///
///
///
public static T Get(IScopeProvider scopeProvider, string key, Func ctor)
where T : ScopeContextualBase
{
// no scope context = create a non-scoped object
var scopeContext = scopeProvider.Context;
if (scopeContext == null)
return ctor(false);
// create & enlist the scoped object
var w = scopeContext.Enlist("ScopeContextualBase_" + key,
() => ctor(true),
(completed, item) => { item.Release(completed); });
w._scoped = true;
return w;
}
///
///
/// If not scoped, then this releases the contextual object.
///
public void Dispose()
{
if (_scoped == false)
Release(true);
}
///
/// Releases the contextual object.
///
/// A value indicating whether the scoped operation completed.
public abstract void Release(bool completed);
}
}