Tuesday, February 13, 2018

Application Initialization and Configuration in ASP.Net Versions

Most of us might have worked upon various versions of ASP.NET and few of you must be aware about the major changes happened in application initialization and configuration phase. In this article, I'll be outlining few of those major changes starting from ASP.NET MVC, ASP.NET Core 1.x and ASP.NET 2.x.
In an era of ASP.NET (prior to ASP.NET Core releases), loading of the application was handled by IIS or say Inetmgr was the one who use to call web application's entry point wherein Global.asax.cs use to provide the Application_Start()method.Below is the sample code snippet take from Global.asax.cx file:

       public class MvcApplication : System.Web.HttpApplication   {        protected void Application_Start()        {               AreaRegistration.RegisterAllAreas();               FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);               RouteConfig.RegisterRoutes(RouteTable.Routes);               BundleConfig.RegisterBundles(BundleTable.Bundles);         }  

In ASP.NET Core 1.x:
Moving on to ASP.NET Core, Global.asax.cs doesn't exusts anymore as the applicaiton initialization process itself has changed a lot. In case of Core, almost all the application initialization and configuration related changed are tale care by two important files named Program.cs and Startup.cs.

Program.cs - This file takes care of web hosting part. Below is the sample code snippet:
public class Program   {           public static void Main(string[] args)           {               var host = new WebHostBuilder()                   .UseKestrel()                   .UseContentRoot(Directory.GetCurrentDirectory())                   .UseIISIntegration()                   .UseStartup<Startup>()                   .Build();                  host.Run();           }  

Startup.cs -  This file takes care of dependency injection and configuration related stuff. Below is the sample code snippet:
public class Startup   {           public Startup()           {           }                // This method gets called by the runtime. Use this method to add services to the container.                  public void ConfigureServices(IServiceCollection services)           {               services.AddMvc();               services.AddScoped<IStudentRepository, StudentRepository>();               services.AddDbContext<ApplicationDbContext>          (c=>c.UserSqlServer(Configuraiton.GetConnectionString("PrimaryConnection")));
        }              // 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();               if (env.IsDevelopment())               {                   app.UseDeveloperExceptionPage();               }                                 app.UseMvc(configureRoutes);               app.Run(async (context) =>               {                   await context.Response.WriteAsync("Hi There!");               });           }              private void configureRoutes(IRouteBuilder routeBuilder)           {                        }   }         

In ASP.NET Core 2.x:
In this version, application initialization and configuration still evolves around these two files named Startup.cs and Program.cs but in much more simplified and with reduced lines of code. Let's have a look at this new Program.cs file:
public class Program   {       public static void Main(string[] args)       {             BuildWebHost(args).Run();       }     
    public static IWebHost BuildWebHost(string[] args) =>               WebHost.CreateDefaultBuilder(args)                   .UseStartup<Startup>()                   .Build();   }   

If you will notice above snippet, it would look very compact. Just three lines, isn't it? Where that entire configuration went which we use to specify in Core 1.x? 

Well, that entire thing is wrapped up in single line via CreateDefaultBuilder method. This method has hide lot many things in itself as: 
- configured the Kestrel along with integration with IIS
- set the current project directory as the root content 
- configured the logging system to make it read from appsettings.json file
- configured reading of environment variables from  appsettings.json file, etc.

Isn't it a cleaner way? 
Happy learning!  

No comments:

Post a Comment