.NET 6 如何使用Startup.cs的解决方案
2022-02-10.NET 6比较典型改变是应用程序从Program.cs和Startup.cs两个文件变为只有一个文件,配合全局using和顶层程序使用,Program.cs只需要简单几句就启动一个程序:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run();
但是很多同学可能怀念以前的使用方式,今天就简单介绍一下,如果你是从.net 6以前升级来的,建议不用做改动, .csproj改下版本就行了。
如果是新建的.net 6 app,想使用Startup.cs,有两种方案。
方案1 引用Startup.cs
var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); var app = builder.Build(); // Fetch all the dependencies from the DI container // var hostLifetime = app.Services.GetRequiredService<IHostApplicationLifetime>(); // As pointed out by DavidFowler, IHostApplicationLifetime is exposed directly on ApplicationBuilder // Call Configure(), passing in the dependencies startup.Configure(app, app.Lifetime); app.Run();
方案2 把Startup.cs的内容集成到Program.cs里面
var builder = WebApplication.CreateBuilder(args); ConfigureConfiguration(builder.configuration); ConfigureServices(builder.Services); var app = builder.Build(); ConfigureMiddleware(app, app.Services); ConfigureEndpoints(app, app.Services); app.Run(); void ConfigureConfiguration(ConfigurationManager configuration) => { } void ConfigureServices(IServiceCollection services) => { } void ConfigureMiddleware(IApplicationBuilder app, IServiceProvider services) => { } void ConfigureEndpoints(IEndpointRouteBuilder app, IServiceProvider services) => { }