简体   繁体   English

如何在 .NET 6 的 Program.cs 中处理请求管道和服务注册

[英]How request pipeline and service registration is handled in Program.cs in .NET 6

Edited--已编辑——
As per my understanding:据我了解:
In .NET 5 , we used to have Startup.cs where service registration is done in ConfigureServices() method and request pipeline is defined in Configure() method..NET 5中,我们曾经有 Startup.cs,其中服务注册在 ConfigureServices() 方法中完成,请求管道在 Configure() 方法中定义。

ConfigureServices() is called once on the startup of the App. ConfigureServices() 在 App 启动时调用一次。
Configure() is called on every request.每次请求都会调用 Configure()。

Whereas in .NET 6 , Service registration and request pipeline are defined in Program.cs.而在.NET 6中,服务注册和请求管道在 Program.cs 中定义。 There is no separation.没有分离。

So the question is,所以问题是,
Do the services get registered on every request?服务是否在每个请求上都注册? If not, how is the request pipeline handled?如果不是,如何处理请求管道?

Please correct me if I'm wrong anywhere:)如果我在任何地方错了,请纠正我:)

A couple of things here:这里有几件事:

Whereas in .NET Core 6, Service registration and request pipeline are defined in Program.cs.

This is not true.这不是真的。 You can still configure your startup class in.Net 6 with UseStartUp.您仍然可以使用 UseStartUp 在.Net 6 中配置您的启动 class。 The recommendation is to do it in Program.cs建议在 Program.cs 中进行

The documentation has more details on how to do this ie, use the minimum hosting model.文档有更多关于如何执行此操作的详细信息,即使用最小托管 model。

Configure() is called on every request.

I think you have misunderstood this.我想你误解了这一点。 It is not the configure method that is going to be called on every request.并不是每个请求都会调用 configure 方法。 The configure method is used to define your middlewares. configure 方法用于定义您的中间件。 The middlewares are the ones that are going to be executed on every request.中间件是要在每个请求上执行的中间件。

Coming to your question,来到你的问题,

Do the services get registered on every request? If not, how is the request pipeline handled?

By using the minimal hosting model, you can still define your middlewares in the Configure() method in your StartUp.cs.通过使用最小托管 model,您仍然可以在 StartUp.cs 的 Configure() 方法中定义中间件。 You just have to call this method explicitly from Program.cs您只需从 Program.cs 显式调用此方法

var builder = WebApplication.CreateBuilder(args);

var startup = new Startup(builder.Configuration);

startup.Configure(app, app.Environment);

A detailed explanation is available in the linked documentation.链接文档中提供了详细说明。 Hope this helps希望这可以帮助

In both .NET 5 and .NET 6 Program.cs holds the program's main method and runs at startup.在 .NET 5 和 .NET 6 中,Program.cs 包含程序的 main 方法并在启动时运行。 It's a simplification to collapse the functionality from Startup.cs into the program main method.将 Startup.cs 中的功能折叠到程序主方法中是一种简化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM