With ASP.NET Core 6.0 projects, you will not find Startup.cs
file. By default, this file is removed and Program.cs
is the new place where you need to register your dependencies and Middleware. But if you are a fan of Startup.cs
or upgrading your project to ASP.NET Core 6.0, you might want back the Startup.cs file. So in this post, let’s find out how to add Startup.cs in ASP.NET Core 6 project.
How to Add Startup.cs in ASP.NET Core 6 Project
With ASP.NET Core 6.0 project, your Program.cs
file would like this. This is the Program.cs
file of ASP.NET Core Web App template.
As you can see here, service and middleware registration is part of this file now. The Startup.cs
has 2 methods in it ConfigureServices()
and Configure()
. We register the dependency/services in ConfigureServices()
and Middlewares in Configure()
method.
Now with new Program.cs
, you need to register your services/dependencies after line no.4 builder.Services.AddRazorPages();
and middleware after line no. 6 var app = builder.Build();
. Remember order matters while registering your middleware in the pipeline.
To add Startup.cs
to ASP.NET Core 6.0 project, add a new file named Startup.cs and add the following code.
This is a very familiar code of Startup.cs
with constructor and those 2 methods. The dependency registration code is removed from the Program.cs
file and put into ConfigureService()
method. And similarly, middleware registration code is also removed from the Program.cs
file and put into Configure()
method.
Next, we need to tell Program.cs
about our Startup.cs
file. So, update Program.cs
file code to the following.
All the required objects by Startup.cs
class is present in builder
object so we can pass the required objects to ConfigureService()
and Configure()
method. That’s it. Your project should run without any error.
What else we can do?
This is a custom way to add Startup.cs
class, so practically we are not bound to follow any inbuilt rules related to this class. I never liked the names ConfigureService()
and Configure()
as these names doesn’t exactly define their purpose. Previously, it wasn’t possible to rename those, but now I can give a meaningful name. Like, ConfigureService
becomes RegisterServices
and Configure
becomes SetupMiddleware
.
That’s it.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
awesome ,material. please share CRUD operations using .Net 6
Thank you so much.