ASP.NET Core 6最小托管模型介绍以及使用原来的Startup类文件
一、ASP.NET Core 6 中的最小托管模型介绍
ASP.NET Core 6相比之前的5.0/3.1版本在程序启动配置相关的代码方面优化了很多,原先两个文件几十行代码优化成了一个文件几行代码就能把程序运行起来,下面来看看部分差异代码。
以前的 Program.cs文件
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebApp { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
Stratup.cs文件
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
ASP.NET Core 6 就只有一个Program.cs文件了
namespace WebApp { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run(); } } }
最少的代码仅需以下这么几行Web程序就能跑起来了
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run();
是不是看着清爽多了。以下代码是部分配置的对比
////////////////////ASP.NET Core 5/////////////////////// public class Startup { public void Configure(IApplicationBuilder app) { // 1.启用某中间件 app.UseStaticFiles(); // 2.启用路由 app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", () => "Hello World"); }); } public void ConfigureServices(IServiceCollection services) { // 3.添加服务 services.AddMemoryCache(); services.AddScoped<ITodoRepository, TodoRepository>(); } } public class Program { public static int Main(string[] args) { CreateHostBuilder(args).Build().Run(); } // 4.配置内容根目录、环境、应用名称 public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseContentRoot(Directory.GetCurrentDirectory()) .UseEnvironment(Environments.Staging) // 5.添加配置提供程序 .ConfigureAppConfiguration(config => { config.AddIniFile("appsettings.ini"); }) // 6.添加日志记录提供程序 .ConfigureLogging(logging => { logging.AddJsonConsole(); }) // 7.自定义 IHostBuilder .ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30)); .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseHttpSys() // 8.自定义 IWebHostBuilder .UseWebRoot("webroot") // 9.更改Web根目录 .UseStartup<Startup>() .UseSetting(WebHostDefaults.ApplicationKey, typeof(Program).Assembly.FullName); }); // 10.自定义依赖注入容器 //.UseServiceProviderFactory(new AutofacServiceProviderFactory()) } ////////////////////ASP.NET Core 6/////////////////////// var builder = WebApplication.CreateBuilder(new WebApplicationOptions { // 4.配置内容根目录、环境、应用名称 ApplicationName = typeof(Program).Assembly.FullName, ContentRootPath = Directory.GetCurrentDirectory(), EnvironmentName = Environments.Staging, WebRootPath = "customwwwroot", // 9.更改Web根目录 //Args = args, WebRootPath = "webroot" }); // 5.添加配置提供程序 builder.Configuration.AddIniFile("appsettings.ini"); // 6.添加日志记录提供程序 builder.Logging.AddJsonConsole(); // 7.自定义 IHostBuilder builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30)); // 8.自定义 IWebHostBuilder builder.WebHost.UseHttpSys(); 10.自定义依赖注入容器 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); // Register services directly with Autofac here. Don't // call builder.Populate(), that happens in AutofacServiceProviderFactory. builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule())); // 3.添加服务 builder.Services.AddMemoryCache(); builder.Services.AddScoped<ITodoRepository, TodoRepository>(); var app = builder.Build(); // 1.启用某中间件 app.UseStaticFiles(); // 2.启用路由 app.MapGet("/", () => "Hello World!"); app.Run();
二、ASP.NET Core 6与原来的Startup文件一起使用
基本上所有6.0以前的老项目都用到了Startup这个文件,里面包含服务配置、中间件配置等各种配置代码,6.0出来变成了单文件还不习惯,不用想这种改变肯定会兼容之前的方式,兼容代码如下:
假设你有如下Startup文件需要继续在6.0的项目中使用
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (!env.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
ASP.NET Core 6的Program文件中使用Startup文件中的代码
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); var app = builder.Build(); startup.Configure(app, app.Environment); app.Run(); } }
就是这么简单,其实就是显示的实例化调用了一下。