Published: October 01 2021

.NET - Startup Class in a Nutshell

Tutorial built with .NET 5.0

Related posts:

The Startup class configures the services available to the .NET Dependency Injection (DI) container in the ConfigureServices() method, and configures the .NET request pipeline for the application in the Configure() method. Both methods are called by the .NET runtime when the app starts, first ConfigureServices() followed by Configure().

The .NET host passes an IApplicationBuilder to the Configure() method, all DI services are also available to Configure() and can be added as parameters to the method (e.g. public void Configure(IApplicationBuilder app, IMyService myService) { ... }). For more info on the startup class and both configure methods see https://docs.microsoft.com/aspnet/core/fundamentals/startup.

A minimal .NET Startup class

Below is an example of a minimal Startup class with the ConfigureServices() and Configure() methods described above, it's from a tutorial I posted recently on how to create a minimal .NET API by hand from scratch, for more info see .NET 5.0 - Bare Bones API Tutorial.

The services.AddControllers() method registers services for controllers with the .NET dependency injection (DI) system.

Routing middleware is added to the request pipeline by calling both app.UseRouting() and app.UseEndpoints(...), the first adds route matching middleware and the second adds endpoint execution middleware to the pipeline. The lambda expression x => x.MapControllers() is passed to app.UseEndpoints() to create endpoints for action methods of attribute routed controllers (controllers decorated with the [Route("...")] attribute).

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace WebApi
{
    public class Startup
    {
        // add services to the DI container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(x => x.MapControllers());
        }
    }
}

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by