C# 如何从Program.cs文件中的appsettings.json文件访问数据库连接字符串
在我的Program.cs文件中,我当前有以下内容: 班级计划 { 静态异步任务主字符串[]args { var serviceHost=新主机生成器; serviceHost.ConfigureAppConfigurationcb=> { cb.AddJsonFileappsettings.json,false; }; serviceHost.ConfigureServicessc=> { //添加我所有的服务。。。 sc.AddDbContextdb=> db.UseSqlServerServer=localdb\\mssqllocaldb;Database=ResultsDatabase;integratedsecurity=True, options=>options.EnableRetryOnFailure5; }; 等待serviceHost.RunConsoleAsync; } } 连接字符串:{ DbContext:Server=localdb\mssqllocaldb;Database=ResultsDatabase;integratedsecurity=True },C# 如何从Program.cs文件中的appsettings.json文件访问数据库连接字符串,c#,sql-server,.net-core,configuration,connection-string,C#,Sql Server,.net Core,Configuration,Connection String,在我的Program.cs文件中,我当前有以下内容: 班级计划 { 静态异步任务主字符串[]args { var serviceHost=新主机生成器; serviceHost.ConfigureAppConfigurationcb=> { cb.AddJsonFileappsettings.json,false; }; serviceHost.ConfigureServicessc=> { //添加我所有的服务。。。 sc.AddDbContextdb=> db.UseSqlServerSer
您可以使用HostBuilderContext类的配置属性获取连接字符串。因此,您需要使用ConfigureServices的重载来帮助您注入HostBuilderContext的实例,如下所示: serviceHost.ConfigureServiceshc,sc=> { sc.AddDbContextdb=> db.UseSqlServerhc.Configuration.GetConnectionStringDbContext, 选项=>options.EnableRetryOnFailure5 ; };
您可以使用HostBuilderContext类的配置属性获取连接字符串。因此,您需要使用ConfigureServices的重载来帮助您注入HostBuilderContext的实例,如下所示: serviceHost.ConfigureServiceshc,sc=> { sc.AddDbContextdb=> db.UseSqlServerhc.Configuration.GetConnectionStringDbContext, 选项=>options.EnableRetryOnFailure5 ; };
In my appsettings.json file I have the connection string:
Is there a way for me to not have to write the entire connection string in my Program.cs file, and instead just refer to "ResultsDatabase" from my appsettings.json file? I have looked at other Stack Overflow articles but most of them talk about the Startup.cs file but I'm looking for it outside of this. If anyone could point me in the right direction that would be great. I am using .Net core