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
28public 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
6public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});Startup
,并依据环境变量进行动态调用依赖注入
Service
的生命周期Transient
Transient
服务在它们每次被服务容器调用的时候创建,通常适用于轻量级和无状态的服务,通过AddTransient
注册Scoped
相对于web
应用程序,指每一次请求的生命周期,通过AddScoped
注册。针对于Entity Framework Core
,AddDbContext
是Scoped
生命周期Singleton
单例模式,从程序启动到关闭,访问同一个实例推荐方式
- 避免通过
GetService
来获取service实例,应该通过依赖注入实现 - 避免在
ConfigureServices
里调用BuildServiceProvider
,调用BuildServiceProvider
会创建两个容器,导致撕裂的单例,并被多个容易引用。应该通过依赖注入的方式在ConfigureServices
注册的时候实现