我试图将IConfiguration(Microsoft.Extensions.Configuration-pkg)注入Program.cs,并且不知道这是否可行,因此,如果可能的话,显然也不知道该怎么做。
我已经在其他项目的Startup类中完成了此操作,但是在这里我只是进行了简单的依赖项注入,在控制台应用程序中,我发现这样做并非相同。
这样做的原因是,关于使用SqlConnection类(System.Data.SqlClient)访问数据库,我需要访问appsettings中的一些键值。
通常,我只是在Startup.cs中添加它:
....
services.AddScoped(mysql => new SqlConnection($"and here goes my variables from appsettings..");
....
我需要使用选项模式还是有更简单的方法?
您将需要自己构建配置。
例如
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句