本文介绍.net6.0中引入的minimal hosting model和如何将.net6.0以前的版本转换成6.0
1. minimal hosting model长啥样
在入门.net的过程中,我发现program.cs里面的写法有些是长这样的:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
有些是长这样的
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>();
});
}
后者看起来更正式一点,所以我以为第一种是闹着玩的,真正的项目是不会这么用的,但是当我仔细看官方文档的时候发现,其实是不同版本的aps.net的写法,第一种是net6.0的,第二种是.net5.0的。
2. 为何引入minimal hosting model
这个结果真是出乎我意料,所以我就去查了一下为啥要改成闹着玩的方式(其实这种方式由自己的名字:minimal hosting model),然后官方的回答是:简单
对比一下可以发现确实简单了很多,以下是两个等同的配置,在.net5.0的时候是:
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>();
});
}
和
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
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();
}
}
很长,但是有用的就那么几句,再来看看.net6.0的:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
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();
刚好把有用的几句摘抄出来了,所以新的版本确实更简单了
3.如何转换成minimal hosting model
重要的就两个:
IServiceCollection
另一个是IApplicationBuilder 和IWebHostEnvironment
转成6.0就是
builder.Services
和app和app.Environment文章来源:https://www.toymoban.com/news/detail-402818.html
参考
https://gist.github.com/davidfowl/0e0372c3c1d895c3ce195ba983b1e03d#custom-dependency-injection-container文章来源地址https://www.toymoban.com/news/detail-402818.html
到了这里,关于【.Net |minimal hosting model 】Program.cs 里面的不同写法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!