我在依赖注入中苦苦寻找单身人士的概念。我不确定是否应该实现类以支持单个/每个实例实例化以用于作为单例的类,或者它们是否应该依赖于程序员对实例化的适当设置。
如果它将在Dependency容器
中标记为singleton,则class将按预期工作...
builder.RegisterType<ApplicationSettings>().AsSelf().SingleInstance();
...
/// <summary>
/// This allows to create many ApplicationSettings instances which each of them will have its collection of settings.
/// Thus we cannot guarantee that one of class has complete settings
/// </summary>
public class ApplicationSettings
{
private readonly object _locker = new object();
private readonly Dictionary<string, object> _settings;
private readonly ILog _log;
public ApplicationSettings(ILog log)
{
_log = log;
_settings = LoadSettings();
Thread.Sleep(3000); //inner hardwork, e.g. cashing of something
}
public object GetSettings(string key)
{
lock (_locker)
{
return _settings.ContainsKey(key) ? _settings[key] : null;
}
}
public void SetSettings(string key, object value)
{
lock (_locker)
{
_settings.Remove(key);
_settings.Add(key, value);
}
}
public void Remove(string key)
{
lock (_locker)
{
_settings.Remove(key);
}
}
public void Save()
{
Thread.Sleep(5000); //Saving somewhere
}
private Dictionary<string, object> LoadSettings()
{
Thread.Sleep(5000); //Long loading from somewhere
return new Dictionary<string, object>();
}
}
所有需要使用ApplicationSettings类的类都将共享一个实例,因此Settings会在保存到某个地方时包含所有信息。另一方面,如果程序员没有将类标记为 SingleInstance ,则在保存时会出现问题,因为如果将其实现为替换存储位置中的整个集合,则不会保存所有设置。因此,正确的功能很大程度上取决于程序员对类的了解并将其用作单例。
在第二个例子中,我使用静态字段进行设置,这允许我使用类作为单例或每个实例的实例化而不影响核心功能(我的意思是如果将使用更多的ApplicationSettings2实例,则不会保存所有设置)< / p>
/// <summary>
/// This allows to create many ApplicationSettings2 instances which each of them will share same collection of settings.
/// </summary>
public class ApplicationSettings2
{
private static readonly object Locker = new object();
private static readonly Dictionary<string, object> Settings;
private readonly ILog _log;
static ApplicationSettings2()
{
Settings = LoadSettings();
Thread.Sleep(3000); //inner hardwork, e.g. cashing of something
}
public ApplicationSettings2(ILog log)
{
_log = log;
}
public object GetSettings(string key)
{
lock (Locker)
{
return Settings.ContainsKey(key) ? Settings[key] : null;
}
}
public void SetSettings(string key, object value)
{
lock (Locker)
{
Settings.Remove(key);
Settings.Add(key, value);
}
}
public void Remove(string key)
{
lock (Locker)
{
Settings.Remove(key);
}
}
public void Save()
{
Thread.Sleep(5000); //Saving somewhere
}
private static Dictionary<string, object> LoadSettings()
{
Thread.Sleep(5000);
return new Dictionary<string, object>();
}
}
两种类使用方法
...
builder.RegisterType<ApplicationSettings>().AsSelf().SingleInstance();
...
或
...
builder.RegisterType<ApplicationSettings>().AsSelf();
...
将导致相同的预期功能。唯一不同的是,单例实例化模式不会导致功能较慢(在ctor中有睡眠),但在一天结束时,更改实例化模式不会破坏任何内容。
我的问题: