AspNet.Core 教程

Asp.net Core 教程

目录

Startup

Startup配置服务和App请求管道

  • ConfigureServices配置程序的services
  • Configure配置程序请求处理的管道
    一个最简单项目的Startup
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    public class Startup
    {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // 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();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
    endpoints.MapGet("/", async context =>
    {
    await context.Response.WriteAsync("Hello World!");
    });
    });
    }
    }

    Startup类在创建程序的host的时候指定,比如
    1
    2
    3
    4
    5
    6
    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
    webBuilder.UseStartup<Startup>();
    });
    通过以上的方式,我们可以创建多个Startup,并依据环境变量进行动态调用

    依赖注入

    Service的生命周期

  • Transient
    Transient服务在它们每次被服务容器调用的时候创建,通常适用于轻量级和无状态的服务,通过AddTransient注册
  • Scoped
    相对于web应用程序,指每一次请求的生命周期,通过AddScoped注册。针对于Entity Framework CoreAddDbContextScoped生命周期
  • Singleton
    单例模式,从程序启动到关闭,访问同一个实例

    推荐方式

  • 避免通过GetService来获取service实例,应该通过依赖注入实现
  • 避免在ConfigureServices里调用BuildServiceProvider,调用BuildServiceProvider会创建两个容器,导致撕裂的单例,并被多个容易引用。应该通过依赖注入的方式在ConfigureServices注册的时候实现

错误处理