最佳答案
在早期版本中,我们使用 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)
{
// Add Services
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Add Middlewares
}
}
现在进去。NET 6(使用 VisualStudio2022)时,我们不会看到 Startup.cs类。看来它的日子不多了。因此,我们如何获得这些对象,如 Configuration (IConfiguration)和 HostEnvironment (IHostEnvironment)
我们如何获得这些对象,比如说从 apptings 读取配置。
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();
我想知道如何从 appsetings.json 读取配置?