在.NET Core 3.0中将IConfiguration注入到Program.cs(控制台应用程序)

9
我正在尝试将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..");
....

我是否需要使用Options模式或者有更简单的方法?


1
你需要自己构建配置。展示你的Program类,让我们看看能否提供帮助。 - Nkosi
1个回答

12

你需要自己构建配置。

例如

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

}

1
当然... 并且在我的情况下,添加 AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 将是最后的修饰。 - nelion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接