.Net Core Startup Class Guide

ssukhpinder

Sukhpinder Singh

Posted on May 12, 2021

.Net Core Startup Class Guide

The Startup class is a single place to configure services and the app's request pipeline.

The Startup class explained as follows:

  • It contains an optional Configure Services method to configure app services. A service is a reusable module that provides functionality.

  • Need to register services in the Configure Services method and consumed throughout the application via dependency injection.

  • Includes a Configure method to build the app’s request processing pipeline.

ConfigureServices and Configure are called by the .NET Core runtime when the app begins executing:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Specify the Startup class in the app’s host built. The Startup class is typically defined by calling the WebHostBuilderExtensions.UseStartup<TStartup> method on the host builder inside the Program.cs file as shown below.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
Enter fullscreen mode Exit fullscreen mode

The host provides services that are accessible to the Startup class constructor. The app attaches additional services via the ConfigureServices method. Both the host and app services are available to Configure and throughout the app.

The following services can be injected into the Startup class constructor:

  • IWebHostEnvironment

  • IHostEnvironment

  • IConfiguration

Multiple Startup Classes

At runtime, the appropriate Startup class is selected when the app defines separate Startup classes for various environments.

The class whose name matches the current environment is prioritized. For example, if the app includes both a Startup class and a StartupDevelopment class, and the app is running in the Development environment, then the StartupDevelopment class will be used.

The ConfigureServices method

The ConfigureServices method is:

  • Optional.

  • To configure the app’s services.

  • To set configuration options.


public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(
            options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddRazorPages();
    }
Enter fullscreen mode Exit fullscreen mode

The Configure method

The Configure function is used to specify how the app responds to different HTTP requests. The pipeline is configured by adding middleware components.

The .NET Core templates configure the pipeline with support for:

  • Developer Exception Page

  • Exception handler

  • HTTP Strict Transport Security (HSTS)

  • HTTPS redirection

  • Static files

  • ASP.NET Core MVC and Razor Pages

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Each Use extension method can be used to add more than one middleware components to the pipeline. For example, the UseStaticFiles method tells the middleware to serve static files.

Each middleware component in the pipeline is responsible for invoking the next element in the channel, if appropriate.

Additional services, such as

  • IWebHostEnvironment

  • ILoggerFactory

  • Anything defined in ConfigureServices

Configure services without Startup

Configure services and the request processing pipeline without using a Startup class, call ConfigureServices, and Configure convenience methods on the host builder.

Multiple calls to ConfigureServices append to one another. If multiple Configure method calls exist, the last Configure call is used.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureServices(services =>
                {
                    services.AddControllersWithViews();
                })
                .Configure(app =>
                {
                    var loggerFactory = app.ApplicationServices
                        .GetRequiredService<ILoggerFactory>();
                    var logger = loggerFactory.CreateLogger<Program>();
                    var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
                    var config = app.ApplicationServices.GetRequiredService<IConfiguration>();

                    logger.LogInformation("Logged in Configure");

                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseExceptionHandler("/Home/Error");
                        app.UseHsts();
                    }

                    var configValue = config["MyConfigKey"];
                });
            });
        });
}
Enter fullscreen mode Exit fullscreen mode

You have learned

  • Startup class methods and their description.

  • Multiple startup classes as per the environment.

  • Create a .Net Core build without Startup class.

Thank you for reading. I hope you like the article..!!

Buy Me A Coffee

💖 💪 🙅 🚩
ssukhpinder
Sukhpinder Singh

Posted on May 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

.Net Core Startup Class Guide
csharp .Net Core Startup Class Guide

May 12, 2021