76

在早期版本中,我们有 Startup.cs 类,我们在启动文件中获取配置对象如下。

public class Startup
{
    private readonly IHostEnvironment environment;
    private readonly IConfiguration config;

    public Startup(IConfiguration configuration, IHostEnvironment environment)
    {
        this.config = configuration;
        this.environment = environment;
    }

    public void ConfigureServices(IServiceCollection services)
    { ... }

    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
    { ... }

}

现在在 .NET 6(使用 Visual Studio 2022)中,我们看不到Startup.cs类。看起来它的日子已经屈指可数了。那么我们如何获取这些对象,例如 Configuration(IConfiguration) 和 Hosting Environment(IHostEnvironment)

我们如何获得这些对象,比如说从 appettngs 读取配置?目前 Program.cs 文件看起来像这样。

using Festify.Database;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<FestifyContext>();


////////////////////////////////////////////////
// The following is Giving me error as Configuration 
// object is not avaible, I dont know how to inject this here.
////////////////////////////////////////////////


builder.Services.AddDbContext<FestifyContext>(opt =>
        opt.UseSqlServer(
            Configuration.GetConnectionString("Festify")));


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

我想从 appsettings 文件中读取配置。

4

6 回答 6

106

WebApplicationBuilderWebApplication.CreateBuilder(args)暴露ConfigurationEnvironment属性返回:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration;
IWebHostEnvironment environment = builder.Environment;

WebApplication返回的WebApplicationBuilder.Build()还暴露ConfigurationEnvironment

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

还要检查迁移指南代码示例

于 2021-10-26T12:16:28.713 回答
10

Program.cs中,创建了如下所示的 WebApplicationBuilder。

var builder = WebApplication.CreateBuilder(args);

一旦我们创建了构建器,配置就可用了。

假设您有默认appSettings.json设置。下面的示例代码将从 JSON 配置文件返回配置默认日志级别设置。

builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"

应用程序运行后,您可以通过应用程序的其他类中的依赖注入访问配置设置。

public MyClass(IConfiguration configuration)
{
   var logLevel = configuration["Logging:LogLevel:Default"];
}

一个值得考虑的好功能是创建一个代表您的设置的类,然后将配置绑定到该类类型的实例。例如,假设您创建了一个MyAppSettings与您的结构相同的新类appSettings.json,您可以执行以下操作:

var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;
于 2021-11-29T21:25:57.120 回答
3

您只需要添加“构建器”即可。在您的配置之前

像:

builder.Services.AddDbContext<FestifyContext>(opt =>opt.UseSqlServer(builder.Configuration.GetConnectionString("Festify")));
于 2021-12-22T07:55:47.763 回答
2

以下代码对我有用:

程序.cs:

var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("conStr");
ConnectionString = connString;

...

partial class Program
{
    public static string? ConnectionString { get; private set; }
}

calling class:
string cnStr = Program.ConnectionString;
于 2022-01-13T15:34:49.810 回答
2

这对我有用---

// Read in from JSON file
builder.Services.Configure<ConnectionKeys>(builder.Configuration.GetSection("ConnectionKeys"));
于 2022-01-17T11:04:11.897 回答
2

.NET 6 已经在 Program.cs 中提供了构建器对象

var builder = WebApplication.CreateBuilder(args);

只需使用此构建器访问配置和环境作为示例,即可从 app.settings.cs 中获取 ConnectionString,如下所示:

builder.Services.AddDbContext<DataContext>( options =>
{
  options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectiion"));
});
于 2022-02-14T16:57:51.663 回答