Home > Software design >  How request pipeline and service registration is handled in Program.cs in .NET 6
How request pipeline and service registration is handled in Program.cs in .NET 6

Time:07-26

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.

ConfigureServices() is called once on the startup of the App.
Configure() is called on every request.

Whereas in .NET 6, Service registration and request pipeline are defined in 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 :)

CodePudding user response:

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. The recommendation is to do it in Program.cs

The documentation has more details on how to do this i.e, use the minimum hosting 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. The configure method is used to define your middlewares. 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. You just have to call this method explicitly from 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

CodePudding user response:

In both .NET 5 and .NET 6 Program.cs holds the program's main method and runs at startup. It's a simplification to collapse the functionality from Startup.cs into the program main method.

  • Related