在早期版本中,我们有 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 文件中读取配置。