.NET5的Program.cs代码迁移至.NET6的实现方法咨询
.NET5 转 .NET6 Program.cs 改造方案
转换后的完整代码
var builder = WebApplication.CreateBuilder(args); // 把原项目CreateHostBuilder里的服务注册逻辑移到这,比如数据库上下文、Identity服务等 // 举个例子: // builder.Services.AddDbContext<StoreContext>(options => // options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // builder.Services.AddDbContext<AppIdentityDbContext>(options => // options.UseSqlServer(builder.Configuration.GetConnectionString("IdentityConnection"))); // builder.Services.AddIdentity<AppUser, IdentityRole>() // .AddEntityFrameworkStores<AppIdentityDbContext>(); var app = builder.Build(); using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService<ILoggerFactory>(); try { var context = services.GetRequiredService<StoreContext>(); await context.Database.MigrateAsync(); await StoreContextSeed.SeedAsync(context, loggerFactory); var userManager = services.GetRequiredService<UserManager<AppUser>>(); var identityContext = services.GetRequiredService<AppIdentityDbContext>(); await identityContext.Database.MigrateAsync(); await AppIdentityDbContextSeed.SeedUsersAsync(userManager); } catch (Exception ex) { var logger = loggerFactory.CreateLogger<Program>(); logger.LogError(ex, "An error occurred during migration"); } } // 把原项目Configure方法里的中间件配置移到这,比如路由、授权等 // 举个例子: // app.UseHttpsRedirection(); // app.UseRouting(); // app.UseAuthorization(); // app.MapControllers(); app.Run();
核心改动点
- 砍掉冗余结构:.NET6支持顶级语句,不用再写
Program类和Main方法,直接编写代码逻辑即可 - 替换Host构建方式:原
CreateHostBuilder(args)替换为WebApplication.CreateBuilder(args),最终通过builder.Build()获取WebApplication实例 - 核心逻辑复用:数据库迁移、种子数据填充的代码基本无需修改,仅需将原代码中的
host替换为app来创建服务作用域 - 补全配置迁移:原
CreateHostBuilder中注册服务的代码(如AddDbContext、AddIdentity)要迁移到builder.Services上;原Configure方法中的中间件配置代码(如UseAuthorization、MapControllers)要放在app实例创建后、app.Run()之前
内容的提问来源于stack exchange,提问作者wrongDestinations
相关产品推荐
相关产品推荐

