Ik gebruik momenteel Unity IoC Container en hier is mijn AppConfig-klasse. Zoals je ziet, zou de Initialize-methode maar één keer moeten worden aangeroepen en ik heb dubbele lock-controle gebruikt om dat te garanderen.
Wat zou de beste manier zijn om dit te bereiken bereiken als mijn aanpak niet de beste manier is?
public interface IAppConfig
{
///
/// Gets the admin username.
///
/// The admin username.
string AdminUsername { get; }
///
/// Gets the admin password.
///
/// The admin password.
string AdminPassword { get; }
///
/// Initializes this instance.
///
void Initialize();
}
///
/// A singleton App config which helps reading from web.config
/// its lifetime is controlled by Unity.
///
public class AppConfig : IAppConfig
{
#region Fields
///
/// the injectable config manager
///
private readonly IConfigManager _configManager;
private readonly ILogger _logger;
private static readonly object LockObject = new object();
private static bool _initialized = false;
#endregion
#region Constructors
///
/// Initializes a new instance of the class.
///
public AppConfig(IConfigManager configManager, ILogger logger)
{
this._configManager = configManager;
this._logger = logger;
}
#endregion
#region Properties
///
/// Gets the admin username.
///
/// The admin username.
public string AdminUsername { get; private set; }
///
/// Gets the admin password.
///
/// The admin password.
public string AdminPassword { get; private set; }
#endregion
#region Methods
public void Initialize()
{
if (_initialized)
{
throw new ApplicationException("Initialize method should be called only once");
}
lock(LockObject)
{
if (_initialized) return;
var adminUserNameSetting = _configManager.AppSettings[ConfigKeys.AdminUsername];
if (adminUserNameSetting == null)
{
throw new ApplicationException("AdminUsername key not found");
}
this.AdminUsername = adminUserNameSetting.Value;
if (String.IsNullOrWhiteSpace(this.AdminUsername))
{
_logger.LogError("AdminUsername not found");
}
//log
var adminPasswordSetting = _configManager.AppSettings[ConfigKeys.AdminPassword];
if (adminPasswordSetting == null)
{
throw new ApplicationException("AdminPassword key not found");
}
this.AdminPassword = adminPasswordSetting.Value;
if (String.IsNullOrWhiteSpace(this.AdminPassword))
{
_logger.LogError("AdminPassword not found");
}
_initialized = true;
}
}
#endregion
}
In de Eenheid gebruik ik de onderstaande code:
// IAppConfig
container.RegisterType(new ContainerControlledLifetimeManager(),
new InjectionConstructor(configManager,
logger));
var appConfig = container.Resolve();
appConfig.Initialize();