bad*_*key 4 c# configuration dependency-injection sqlconnection appsettings
我正在尝试将 IConfiguration(Microsoft.Extensions.Configuration 包)注入 Program.cs 中,但不知道这是否可行,因此如果可能的话,显然不知道该怎么做。
我已经在其他项目的 Startup 类中完成了它,但在那里我只是做了一个简单的依赖注入,我没有发现在控制台应用程序中以相同的方式完成。
原因是,我需要访问 appsettings 中的一些关键值,以使用 SqlConnection 类 (System.Data.SqlClient) 访问我的数据库。
通常,我只是在 Startup.cs 中像这样添加它:
....
services.AddScoped(mysql => new SqlConnection($"and here goes my variables from appsettings..");
....
Run Code Online (Sandbox Code Playgroud)
我需要使用选项模式还是有更简单的方法?
您需要自己构建配置。
例如
static void Main(string[] args) {
var builder = new ConfigurationBuilder()
//.SetBasePath("path here") //<--You would need to set the path
.AddJsonFile("appsettings.json"); //or what ever file you have the settings
IConfiguration configuration = builder.Build();
//...use configuration as needed
}
Run Code Online (Sandbox Code Playgroud)