Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Understanding Startup.cs file in ASP.NET 5

0.00/5 (No votes)
6 Jan 2016 1  
Understanding Startup.cs file in ASP.NET 5

Introduction

Startup.cs file is a replacement of Global.asax file in ASP.NET Web Form application. We know that Global.asax is an optional file to handle Application level event in ASP.NET application. In ASP.NET 5, Startup.cs file has introduce to server same.

Though the purpose is the same, the implementation of Startup.cs file is entirely different. Global.asax file contains mostly application level pre-defined events where Startup.cs file is more about registering services and injection of modules in HTTP pipeline. Startup.cs file contains Startup class which triggers at first when application launches and even in each HTTP request/response.

Actually, the inception of Startup class is in OWIN application which is a specification to reduce dependency of application on server.

Startup class is allowed to put in any namespace, but the class name must not change. In runtime, it looks for Startup keyword in metadata.

Now the question may come, is startup class mandatory in application? Yes, startup class is mandatory in each ASP.NET 5 application. It can be decorated with any access specifier. Multiple Startup classes are allowed in a single application. ASP.NET will select the appropriate class based on its namespace. Here is rule to select.

At first, it matches with project’s root namespace first, otherwise using the class in the alphabetically first namespace.

Here is an example of a typical startup class which will scaffold once you choose empty ASP.NET5 template.

public class Startup
{
    //For more information on how to configure your application,
    //visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

    }

    public void Configure(IApplicationBuilder app)
    {

    }
}

Startup Constructor

We can specify constructor of a Startup class and by default, it takes three parameters:

public class Startup
{

    public Startup(IApplicationEnvironment env,
                   IHostingEnvironment hostenv,  ILoggerFactory logger)
    {
    }

IApplicationEnvironment interface contains method and property related to current environment. Mostly, it can deal with environment variables in application.

IHostingEnvironment interface deals with current hosting environment of application. It could be development, UAT or production. Based on hosting environment, we can change behavior of application.

IloggerFactory interface is to provide default logging service in ASP.NET 5 application. It supports various options to implement logging.

Now, let’s understand ConfigureService and Configure methods now.

ConfigureService Method

This is an optional method in Startup class which is used to configure services which will be used by application. Once the application launches and when first request comes, it hits the ConfigureService method. The method must be declared as public visibility scope otherwise environment will not be able to read the content from metadata. Here, we have defined ConfigureService in private mode and seeing that:

It was not able to attach MVC service.

ConfigureService method expects implementation of IServiceCollection type as argument which is needed to register the services. ConfigureService method executes before Configuration method because sometimes, it needs to register the service before injecting to HTTP pipeline. IServiceCollection interface has implemented in many classes so that it offers many Add[something] extension methods to register services. Here, we are seeing a couple of extension methods like AddAutnentication(), AddCors() etc. to register respective services.

Not only the default services, we can register the dependencies which will be used in application in ConfigurationService method. In this example, we will use default IoC container of ASP.NET5. Here, we have created ILog interface and implemented in Log class.

public interface ILog { }
public class Log : ILog { }

This is how we can register the dependency by calling AddTransient<T,T>() method:

public void ConfigureServices(IServiceCollection services)
       {
           services.AddMvc();
           services.AddTransient<ILog, Log>();
       }

Now, we are allowed to use ILog in any controller and in runtime, the implementation of Ilog will server automatically.

Configure Method

The Config method is used to specify how the application will respond in each HTTP request. Which implies that Configure method is HTTP request specific. The most typical use of configure method is to inject middleware in HTTP pipeline. The configure method must accept IApplicationBuilder parameter with some optional in build services like IHostingEnvironment and ILoggerFactory. Once we add some service in ConfigureService method, it will be available to Configure method to be used. That’s why ConfigureService executes before Configure. For example:

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

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }

To use UseMvc() extension method in Configure(), we need to add MVC service in ConfigureService() method at first by calling AddMvc(), because MVC framework is not shipped by default in ASP.NET architecture.

Here is a very common operation which we can perform in Configure method.

public void Configure(IApplicationBuilder app ,
IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //Add MVC module and specify Root
        app.UseMvc();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        //Perform environment specific task
        if (env.IsDevelopment())
        {
            //When it is dev environment
        }else
        {
            //Other then Development
        }
        //Add static file module
        app.UseStaticFiles();
        //Use Identity Module
        app.UseIdentity();
    }

Besides that, we can inject our own middleware in HTTP pipeline within Configure() method. Here is one small example of the same.

    public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
            app.Run(async context =>
            {
                await context.Response.WriteAsync("Return From Run.");
            });
}

We have attached our own HTTP handler in Run() extension which will short circuit all HTTP requests and return HTTP response from there itself.

Conclusion

Startup class is the entry point of ASP.NET 5 application like Global.asax in an earlier version of ASP.NET. Application may have more than one startup class but ASP.NET will handle such a situation gracefully. Startup class is mandatory in ASP.NET 5 application.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here