我有一个使用EF Core的控制台应用程序,如下所示。
static class Program
{
private static readonly IConfiguration _configuration;
static Program()
{
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
}
private static void ConfigureServices(IServiceCollection isc)
{
isc.AddSingleton(_ => _configuration);
// others are removed for simplicity
isc.AddSingleton<TheApp>();
}
public static IServiceProvider CreateServiceProvider()
{
// create service collection
IServiceCollection isc = new ServiceCollection();
ConfigureServices(isc);
// create service provider
return isc.BuildServiceProvider();
}
private static void Main(string[] args)
{
// create application instance and run
using (var scope = CreateServiceProvider().CreateScope())
{
scope.ServiceProvider.GetRequiredService<TheApp>().Run();
}
}
}
存在Singleton
,Transient
,Scoped
个生存时间。哪一个适合上面的静态字段_configuration
?生命时间重要吗?
答案 0 :(得分:1)
Singleton
,因为一旦设置了配置,就应该只使用该配置。