Click here to Skip to main content
14,207,870 members
Click here to Skip to main content
Add your own
alternative version

Stats

89K views
17 bookmarked
Posted 6 Jan 2016
Licenced CPOL

Understanding Startup.cs file in ASP.NET 5

, 6 Jan 2016
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sourav Kayal
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
QuestionServer same ?? Pin
Member 141726275-Mar-19 20:28
memberMember 141726275-Mar-19 20:28 
QuestionGood one Pin
Debendra025629-Jan-18 5:50
memberDebendra025629-Jan-18 5:50 
QuestionConsole App Pin
Assil13-Feb-16 7:33
professionalAssil13-Feb-16 7:33 
QuestionTypo Pin
thelon7-Jan-16 20:50
memberthelon7-Jan-16 20:50 
Generalsome fixes are required Pin
Oleg Kiriljuk7-Jan-16 2:48
memberOleg Kiriljuk7-Jan-16 2:48 
GeneralRe: some fixes are required Pin
Islamegy5-Mar-17 3:11
memberIslamegy5-Mar-17 3:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190612.1 | Last Updated 6 Jan 2016
Article Copyright 2016 by Sourav Kayal
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid