我想在整个应用程序中使用以下Singleton类:
public sealed class AppSettings
{
private static readonly Lazy<AppSettings> _lazy =
new Lazy<AppSettings>(() => new AppSettings());
private AppSettings()
{
// I want to inject this
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);
Config = builder.Build();
}
public static AppSettings Instance => _lazy.Value;
public IConfigurationRoot Config { get; }
}
我想注入IConfiguration,而不是在其中构建它。这是最好的方法吗?
答案 0 :(得分:3)
您不需要创建自己的单例类。相反,创建一个普通类并将其注册/添加到DI容器中作为singleton:
public sealed class AppSettings
{
private IConfiguration _configuration;
public AppSettings(IConfiguration configuration)
{
_configuration = configuration;
}
...
}
然后在ConfigureServices
方法中使用
// IConfigurationRoot ConfigureServices;
services.AddSingleton(new AppSettings(Configuration));