Open In App

Explain ConfigureServices and Configure method in ASP.NET ?

In this article, we will see what is Configure and ConfigureService methods. Basically, these two methods play a very important role in startup class. The baseline of this class is to reduce the dependency of the application on the server. Actually, The Startup class is required to define two methods that will be invoked automatically by ASP.NET Core. They are the ConfigureServices method and the Configure method.  

In the Startup class, we actually do two things:



Example: Open the program.cs file. As you can see the code:




using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
  
namespace Avengers_ListApplicaton {
    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> ();
            });
    }
}

Startup.cs: Let’s take a look at the Startup class. as we see the ConfigureServices and the Configure method.






namespace Avengers_ListApplicaton {
    public class Startup {
        
        // This method gets called by the runtime. 
          // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Register services here through dependency injection
        }
  
        // This method gets called by the runtime. 
          // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, 
                              IWebHostEnvironment env) {
            
            // Add middlware components here
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                endpoints.MapGet("/",async Context => {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

In the ConfigureServices method:

In the Configure method:

This one is called after configuring service method because it uses services that are registered and configured in configureServices method

Let’s see now, how to decorate the services in startup.cs file.Create a simple project,

In this project, I will not be going to explain or define each and every step. In which we are going to focus on only startup.cs file

So Let’s get started:

Step 1: create a new asp.net core web application project and select template MVC

Step 2: Create Model class under model folder i.e ToDoModel




public class ToDoModel {
    public int Id { get; set; }
    [Required]
    [MaxLength(50)]
    public string Wish{ get; set; }
}

Step 3: Create Class ApplicationDbContext | Inherits DbContext class | Add Constructor | Add model class to ApplicationDbContext




public class ApplicationDbContext : DbContext {
    public ApplicationDbContext(
          DbContextOptions<ApplicationDbContext> options)
             : base(options) {
    }
         
    public DbSet<ToDoModel> ToDoData { get; set; }
}

Note : In this demo, I am going to use InMemory database with Entity Framework Core. So you have to install the nuget package of it i.e Microsoft.EntityFrameworkCore.InMemory.

Step 4: Now let’s register the services in the ConfigureServices method, 




public void ConfigureServices(IServiceCollection services) {
      services.AddMvc();
    services.AddDbContext<ApplicationDbContext>(
        options => options.UseInMemoryDatabase("ToDoList"));
}

Step 5: In the Configure method, remove existing code entirely and replace it with a call to app.UseRouting() and after UseRouting add a call to app.UseEndpoints().

UseRouting: This Middleware component is used to route requests.

UseEndpoints: This middleware component will enable routing the request to the correct endpoint in the application. 




public void Configure(IApplicationBuilder app, 
                      IWebHostEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    }
    else {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseRouting();
  
    app.UseEndpoints(endpoints => {
        endpoints.MapDefaultControllerRoute();
    });
}

Step 6: In the Configure method before UseRouting, checks the environment  if env is set to Development using the IsDevelopment() method 

Step 07: Create controller HomeController | Add action methods i.e Index and Error |




public class HomeController : Controller {
    public IActionResult Index() {
        return View("Index");
    }
    public IActionResult Error() {
        return View("Error");
    }
}

Step 08: In the shared folder create generic error view and also for add view to index method | On that index view add link of ToDoList

Error action method View :




@{
    ViewData["Title"] = "Error";
}
  
<h1>Error</h1>
  
  
<p>An error has occurred. Please try again.</p>

Index action method of Homecontroller view :




@model IEnumerable<ToDoList.Models.ToDoModel>
  
@{
    ViewData["Title"] = "Index";
}
  
<h1>Index</h1>
  
@Html.ActionLink("View Task List", "Index", "ToDo")

Step 9: Create one more controller | create field of type ApplicationDbContext. | Create constructor and set the value to the parameter passed to constructor | Create action methods for list | Get Create | Post Create and based on it add views 




public class ToDoController : Controller
    {
        private readonly ApplicationDbContext _context;
  
        public ToDoController(ApplicationDbContext context)
        {
             _context = context;
        }
        public IActionResult Index()
        {
            var model=_context.ToDoData.ToList();
            return View("Index",model);
        }
        [HttpGet]
        public IActionResult Create()
        {
            return View("Create");
        }
        [HttpPost]
        public IActionResult Create(ToDoModel todo)
        {
            _context.ToDoData.Add(todo);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
         
    }

Output:

Output GIF

Last Thought,

Startup Flow of application

Let’s a quick highlight some points article. The application starts with the call to the main function in the Startup class. Then, we specified which was our Startup class using the startup call. In the Startup class, first, ConfigureServices is called, allowing us to register services that we’ll want to use in our application. Then, the Configure method is called where the request pipeline is set up. After all that, our application is up and running and is ready to handle incoming requests.

That is all about Configure and ConfigureService Methods.


Article Tags :