JumpStart # 43 – Understanding Program and Startup classes in ASP.Net Core Application

Program and Startup classes are breaking changes in ASP.Net 5 (although they are existed in unified Startup class, in ASP.Net Core they are diverged into separate classes) which are used to start the application and support application’s HTTP pipeline. In previous versions of ASP.Net we have Global.asax which exposes different events at application life cycle level. In this jumpstart, we are going to see what is the relevance of both classes in ASP.Net Core Application.

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

 image

ASP.Net Core application is a Console Application, where static void Main() entry point is located in Program class.

public class Program
{
    public static void Main(string[] args)
    {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
    }
}

ASP.Net Core application require an host to start the application and manage application’s lifetime. WebHostBuilder is used to configure and launch the host. Above code creates a host which uses Kestrel server with content root set to current application’s directory. We need to set UseIISIntegration to use IIS as a reverse proxy server (if in case we want to host our application in IIS). Then we will set Startup class to add and resolve services and create HTTP pipeline (we can also use WebHostBuilder’s Configure and ConfigureServices as an alternative to Startup class). We can also set other properties like Configuration, Server URLs, Application settings etc., using WebHostBuilder. Finally we will call Build to create the host and then Run to start it.

Startup class is mainly used for setting up the configuration, add services and handle the HTTP pipeline of all requests made to the application.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AspNetCore
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
           
            if (env.IsEnvironment("Development"))
            {
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddCors();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
                
                app.UseApplicationInsightsRequestTelemetry();
                app.UseApplicationInsightsExceptionTelemetry();

                app.UseMvc();
        }
    }
}

Startup class constructor is used to set the Configuration for the application. Typically all the configuration is maintained in appsettings.json file and it is loaded using IConfigurationRoot. Constructor is also used to load the Environment variables.

ConfigureServices method is used to add services (IServiceCollection) to application through Dependency Injection (ASP.Net Core supports DI by default). In ASP.Net Core everything is service based, in fact MVC is also a service (MVC is added using AddMvc()). Similarly we can add EntityFramework, CORS etc., services. There are many 3rd party nuget packages which supports different functionalities, all these services can be added and configured in this method.

Configure method is used to configure the HTTP Pipeline for every request. IApplicationBuilder is used to add services to the pipeline. In above code, we see logging, application insights and MVC are added to the pipeline. Apart from the services which are added to the pipeline, no other services will be executed for any request. Custom middleware can be added to pipeline using Configure method. Order of execution of services depends on the order which they are added.

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...