gpt4 book ai didi

c# - ASP.NET Core 中的 ConfigureServices() 和 Configure() 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 02:59:37 25 4
gpt4 key购买 nike

learn.microsoft.com 上的文档说明如下:

Use ConfigureServices method to add services to the container.

Use Configure method to configure the HTTP request pipeline.

谁能用简单的例子解释一下,什么是向容器添加服务,什么是配置 HTTP 请求管道?

最佳答案

简而言之:

ConfigureServices用于配置依赖注入(inject)

public void ConfigureServices(IServiceCollection services)
{
// register MVC services
services.AddMvc();

// register configuration
services.Configure<AppConfiguration>(Configuration.GetSection("RestCalls"));

// register custom services
services.AddScoped<IUserService, UserService>();
...
}

Configure用于设置中间件、路由规则等

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// configure middlewares
app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseMiddleware<ExceptionHandleMiddleware>();

app.UseStaticFiles();

// setup routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Default",
template: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = 1 });

});
}

阅读ASP.NET Core fundamentals详细了解它的工作原理。

关于c# - ASP.NET Core 中的 ConfigureServices() 和 Configure() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com