using System;
using System.Collections.Generic;
using Abp.Collections.Extensions;
namespace Abp.Configuration
{
///
/// Used to set/get custom configuration.
///
public class DictionaryBasedConfig : IDictionaryBasedConfig
{
///
/// Dictionary of custom configuration.
///
protected Dictionary CustomSettings { get; private set; }
///
/// Gets/sets a config value.
/// Returns null if no config with given name.
///
/// Name of the config
/// Value of the config
public object this[string name]
{
get { return CustomSettings.GetOrDefault(name); }
set { CustomSettings[name] = value; }
}
///
/// Constructor.
///
protected DictionaryBasedConfig()
{
CustomSettings = new Dictionary();
}
///
/// Gets a configuration value as a specific type.
///
/// Name of the config
/// Type of the config
/// Value of the configuration or null if not found
public T Get(string name)
{
var value = this[name];
return value == null
? default(T)
: (T) Convert.ChangeType(value, typeof (T));
}
///
/// Used to set a string named configuration.
/// If there is already a configuration with same , it's overwritten.
///
/// Unique name of the configuration
/// Value of the configuration
public void Set(string name, T value)
{
this[name] = value;
}
///
/// Gets a configuration object with given name.
///
/// Unique name of the configuration
/// Value of the configuration or null if not found
public object Get(string name)
{
return Get(name, null);
}
///
/// Gets a configuration object with given name.
///
/// Unique name of the configuration
/// Default value of the object if can not found given configuration
/// Value of the configuration or null if not found
public object Get(string name, object defaultValue)
{
var value = this[name];
if (value == null)
{
return defaultValue;
}
return this[name];
}
///
/// Gets a configuration object with given name.
///
/// Type of the object
/// Unique name of the configuration
/// Default value of the object if can not found given configuration
/// Value of the configuration or null if not found
public T Get(string name, T defaultValue)
{
return (T)Get(name, (object)defaultValue);
}
///
/// Gets a configuration object with given name.
///
/// Type of the object
/// Unique name of the configuration
/// The function that will be called to create if given configuration is not found
/// Value of the configuration or null if not found
public T GetOrCreate(string name, Func creator)
{
var value = Get(name);
if (value == null)
{
value = creator();
Set(name, value);
}
return (T) value;
}
}
}