ASP.NET Core中的ConfigureServices()和Configure()之间有什么区别? [英] What are the differences between ConfigureServices() and Configure() in ASP.NET Core?
问题描述
docs.microsoft.com上的文档规定以下内容:
The documentation on docs.microsoft.com states the following:
使用ConfigureServices方法将服务添加到容器中.
Use ConfigureServices method to add services to the container.
使用Configure方法配置HTTP请求管道.
Use Configure method to configure the HTTP request pipeline.
有人可以用简单的例子来说明,向容器添加服务是什么意思,以及配置HTTP请求管道是什么意思?
Can someone explain with simple examples, what is meant by adding services to container and what is meant by configuring HTTP request pipeline?
推荐答案
简而言之:
ConfigureServices
用于配置依赖注入
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
用于设置中间件,路由规则等
Configure
is used to set up middlewares, routing rules, etc
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核心基础知识,以了解其工作原理详细信息.
Read ASP.NET Core fundamentals to understand how it works in details.
这篇关于ASP.NET Core中的ConfigureServices()和Configure()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!