当前位置:主页 > 软件编程 > .NET代码 >

.Net 6简介并和之前版本写法做对比

时间:2023-01-07 09:28:58 | 栏目:.NET代码 | 点击:

介绍

vs2022正式版已经推出了,估计很多人已经下载并开始创建.Net 6 开始尝鲜了, 本节我简要的给大家介绍一下.Net 6的一些改动。

正文

本次.Net6带来最明显的变化就是:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.Run();

对于这样的改动大家可能会觉得这是C# 10 带来的优化,但我的理解是.Net6为了新手更加方便入门,早期我们使用.Net Core 2/3/5 版本,还要给新人解释系统启动入口Program.Main()以后不需要了,配置拆分成两个文件Program.cs和Startup.cs虽然做到了关注点分离,但是对于新人会难以理解这次也没了,当我们讨论Startup的时候不用在去解释如何调用的2个约定方法,即使它们没有显式实现接口,也可以调用它们。

我们来看一下之前的语法,我们有一大堆嵌套的 lambda,代码看上去非常复杂。

var hostBuilder = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services => 
    {
        services.AddControllers();
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.Configure((ctx, app) => 
        {
            if (ctx.HostingEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", () => "Hello World!");
                endpoints.MapRazorPages();
            });
        });
    }); 

hostBuilder.Build().Run();

升级到.Net 6之后,我们可以使用更简单的 API 来实现。

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();

对比

我们将 2个版本的语法对比来看

向DI 容器添加服务

var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureServices(services => 
    {
        services.AddControllers();
        services.AddSingleton<MyThingy>();
    })


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSingleton<MyThingy>();

日志记录

var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureLogging(builder => 
    {
        builder.AddFile();
    })

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddFile();

Serilog 集成

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog() // <-- Add this line
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });


builder.Host.UseSerilog();

完成的来看效果

    public interface IHelloService
    {
        string Hello(bool isHappy);
    }

    public class HelloService : IHelloService
    {
        public string Hello(bool isHappy)
        {
            var hello = $"Hello World";

            if (isHappy)
                return $"{hello}, you seem to be happy today";
            return hello;
        }
    }


using MinimalApiDemo;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IHelloService, HelloService>();
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.MapGet("/Hello", (bool? isHappy, IHelloService service) =>
{
    if (isHappy is null)
        return Results.BadRequest("Please tell if you are happy or not :-)");

    return Results.Ok(service.Hello((bool)isHappy));
});


app.Run();

您可能感兴趣的文章:

相关文章