Explain ConfigureServices and Configure method in ASP.NET ?
Last Updated :
22 Mar, 2022
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:
- Configure Service(): It is used to add services to the container and configure those services. basically, service is a component that is intended for common consumption in the application. There is framework service like MVC, EF core, identity so on. but there are also application services that are application-specific like send mail services.
- Configure(): it is used to specify how the asp.net core application will respond to individual requests. Through this, we actually build the HTTP request pipeline
Example: Open the program.cs file. As you can see the code:
C#
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> ();
});
}
}
- In the main function, a host is set up, which will configure a server and a request processing pipeline.
- We are calling the CreateHostBuilder, which will set up an application with some defaults using the Host.CreateDefaultBuilder().
- In the Main, we will call the CreateHostBuilder, and in there a host will be created that will then run our application. You can see that we are first going to call on the host the CreateDefaultBuilder method. The CreateDefaultBuilder method will set up a host builder with quite some defaults already. the new web host will be configured again with defaults.
- Another very important thing that is happening here is that we are specifying the Startup class using the UseStartup method. We are passing as a type the Startup class i.e UseStartup<Startup>, which will be the type that actually performs the configuration of the application.
Startup.cs: Let's take a look at the Startup class. as we see the ConfigureServices and the Configure method.
C#
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 ConfigureServices method, which will be called first, we will be registering our services for the application
- As you can see, in the above code snippet initially there is no code in ConfigureService but regardless of that, those built-in services are already available for injection so all the services we can add in this method and inject into other pieces of code.
- This container is available through the IServiceProvider interface, and the service collection you see here is the collection of services that it manages. So we can, in the ConfigureServices method, add the services to the collection of managed services in the application. Services are objects with fixed functionality for other parts of the application
- In there, we need to add all the services that we will be using inside of our application. Those can be built-in services, as well as our own services. This is the place where we will be registering all dependencies with the dependency injection system built-in to ASP.NET Core.
In the Configure method:
This one is called after configuring service method because it uses services that are registered and configured in configureServices method
- The HTTP request pipeline will be configured. There are some defaults in here as you can see, and notice that the first line is going to use an environment check. Using dependency injection, this method will receive a WebHostEnvironment instance, and on that, we are going to check the environment.
- The env.IsDevelopment This signifies that this developer-friendly exception page middleware will only be added when we are running in a development environment. The developerExceptionPage middleware is not something we want to allow everyone to see. we want stack traces of exception only during the development app.UseDeveloperExceptionPage statement configures the request pipeline by adding the developerExceptionPage middleware to it so now when an exception is thrown, the piece of code which you see in the code snippet will handle it.
- Now I am going to add another piece of code that handles exceptions that do not belong to the development environment. The useExceptionHandler middleware catches the exception, logs them, and then re-executes the request. This will not show us a developer-friendly exception page and stack trace won't be exposed. Now you can check by changing the environment variable.
- well, come to next UseRouting and UseEnpoints.it is actually responsible to give the response as an output when a request was sent to the application was going to respond by sending to response a string saying 'Hello world' so the used routing and endpoints middlewares basically enable the MVC to respond to an incoming request it needs to map incoming requests with the correct code that will execute
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
C#
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
C#
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,
- call AddMvc() to add support for MVC middleware.
- call AddDbContext<> with the argument of .UseInMemoryDatabase("ToDoList") to configure EntityFramework to the DbContext class.
C#
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.
C#
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
- If Yes, it should call app.UseDeveloperExceptionPage() to get stack trace of error pages.
- Otherwise, it should call app.UseExceptionHandler() and pass it the argument "/Home/Error"
- UseDeveloperExceptionPage: This will enable the use of the developer exception page in my application, so that will get useful information during development.
- UseExceptionHandler: This middleware component is used to enable to addition of custom user-friendly error messages.
Step 07: Create controller HomeController | Add action methods i.e Index and Error |
C#
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 :
HTML
@{
ViewData["Title"] = "Error";
}
<h1>Error</h1>
<p>An error has occurred. Please try again.</p>
Index action method of Homecontroller view :
HTML
@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
C#
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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read