using System;
namespace Swan.Configuration
{
///
/// Base class for objects whose configuration may be locked,
/// thus becoming read-only, at a certain moment in their lifetime.
///
public abstract class ConfiguredObject
{
private readonly object _syncRoot = new object();
private bool _configurationLocked;
///
/// Gets a value indicating whether s configuration has already been locked
/// and has therefore become read-only.
///
///
/// if the configuration is locked; otherwise, .
///
///
protected bool ConfigurationLocked
{
get
{
lock (_syncRoot)
{
return _configurationLocked;
}
}
}
///
/// Locks this instance's configuration, preventing further modifications.
///
///
/// Configuration locking must be enforced by derived classes
/// by calling at the start
/// of methods and property setters that could change the object's
/// configuration.
/// Immediately before locking the configuration, this method calls
/// as a last chance to validate configuration data, and to lock the configuration of contained objects.
///
///
protected void LockConfiguration()
{
lock (_syncRoot)
{
if (_configurationLocked)
return;
OnBeforeLockConfiguration();
_configurationLocked = true;
}
}
///
/// Called immediately before locking the configuration.
///
///
protected virtual void OnBeforeLockConfiguration()
{
}
///
/// Checks whether a module's configuration has become read-only
/// and, if so, throws an .
///
/// The configuration is locked.
///
protected void EnsureConfigurationNotLocked()
{
if (ConfigurationLocked)
throw new InvalidOperationException($"Configuration of this {GetType().Name} instance is locked.");
}
}
}