Thursday, October 2, 2025

🚀 Understanding Middleware and Dependency Injection (DI) in ASP.NET Core with Examples

When building modern web applications using ASP.NET Core, two concepts you cannot ignore are Middleware and Dependency Injection (DI). These are the backbone of the framework, ensuring clean architecture, scalability, and maintainability.

In this article, we will dive deep into:

  • What is Middleware in ASP.NET Core?

  • Real-world examples of Middleware.

  • What is Dependency Injection (DI)?

  • Types of Dependency Injection in .NET Core.

  • Code examples for both Middleware and DI.

By the end, you’ll not only understand these concepts but also be ready to confidently explain them in interviews or implement them in real projects.


🔹 What is Middleware in ASP.NET Core?

Middleware is a component in the HTTP request/response pipeline of an ASP.NET Core application. Every request that comes to the server passes through a series of middleware components before reaching the controller (or endpoint). Each middleware can:

  1. Perform an action before passing the request forward.

  2. Call the next middleware in the pipeline.

  3. Perform an action on the response before sending it back.

👉 In simple words: Middleware acts like a chain of checkpoints where each component can process requests and responses.


✅ Real-World Analogy for Middleware

Imagine an airport security check:

  • First, your ticket is verified (Authentication Middleware).

  • Next, your luggage goes through scanning (Authorization Middleware).

  • Finally, customs may inspect your items (Custom Middleware).

Only then are you allowed to board the plane (Endpoint execution).


✅ Example of Middleware in ASP.NET Core

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Custom Middleware app.Use(async (context, next) => { Console.WriteLine("Request Path: " + context.Request.Path); await next.Invoke(); // Pass to next middleware Console.WriteLine("Response Status: " + context.Response.StatusCode); }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World from Middleware!"); }); }); }

Explanation:

  • First middleware logs the request and response.

  • UseRouting handles route matching.

  • UseAuthorization checks permissions.

  • Endpoint returns the final response.

👉 SEO Keywords: Middleware in ASP.NET Core, ASP.NET Core pipeline, custom middleware in .NET Core, request response pipeline in ASP.NET Core.


🔹 What is Dependency Injection (DI) in ASP.NET Core?

Dependency Injection (DI) is a design pattern where objects receive their dependencies from an external container instead of creating them directly.

👉 This ensures loose coupling, easy testing, and maintainability of code.


✅ Real-World Analogy for DI

Think of a car:

  • The car requires an engine.

  • Instead of the car building its own engine, we inject an engine from outside.

  • This way, we can replace a PetrolEngine with a DieselEngine without changing the car itself.


✅ Example without DI (Tightly Coupled Code)

public class Car { private PetrolEngine _engine; public Car() { _engine = new PetrolEngine(); // tightly coupled } public void Drive() { _engine.Start(); Console.WriteLine("Car is running..."); } }

❌ Problem: If we want to use DieselEngine, we must modify the Car class.


✅ Example with DI (Loosely Coupled Code)

// 1. Abstraction public interface IEngine { void Start(); } // 2. Implementations public class PetrolEngine : IEngine { public void Start() => Console.WriteLine("Petrol Engine Started"); } public class DieselEngine : IEngine { public void Start() => Console.WriteLine("Diesel Engine Started"); } // 3. Car depends on abstraction public class Car { private readonly IEngine _engine; public Car(IEngine engine) // Constructor Injection { _engine = engine; } public void Drive() { _engine.Start(); Console.WriteLine("Car is running..."); } }

✅ Registering DI in ASP.NET Core

var builder = WebApplication.CreateBuilder(args); // Register services builder.Services.AddScoped<IEngine, PetrolEngine>(); var app = builder.Build(); app.MapGet("/drive", (Car car) => { car.Drive(); return "Driving with Dependency Injection!"; }); app.Run();

Here, the ASP.NET Core built-in DI container automatically injects the dependency (IEngine) when creating Car.



🔹 Types of Dependency Injection in ASP.NET Core

  1. Constructor Injection (most common) → Dependencies are passed via constructor.

  2. Method Injection → Dependencies are passed as method parameters.

  3. Property Injection → Dependencies are set using public properties.


🔹 DI Lifetimes in ASP.NET Core

  • Transient → New instance is created every time.

  • Scoped → One instance per request.

  • Singleton → One instance for the entire application.

Example:

builder.Services.AddTransient<IService, MyService>(); // Every time new builder.Services.AddScoped<IService, MyService>(); // Per request builder.Services.AddSingleton<IService, MyService>(); // One for all

📝 Summary

  • Middleware in ASP.NET Core controls how requests and responses flow through the pipeline. You can build custom middleware for logging, error handling, or authentication.

  • Dependency Injection (DI) helps reduce tight coupling by injecting dependencies instead of creating them inside classes. ASP.NET Core comes with a powerful built-in DI container.

These two features are core to building clean, scalable, and testable web applications in ASP.NET Core

No comments:

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages