👉 Middleware uses services, and those services can be Singleton, Scoped, or Transient.
Let’s see a clear practical example 👇
🔹 1. Create Services with Different Lifetimes
✅ Singleton Service (same instance for entire app)
public class SingletonService
{
public Guid Id { get; } = Guid.NewGuid();
}
✅ Scoped Service (new per request)
public class ScopedService
{
public Guid Id { get; } = Guid.NewGuid();
}
✅ Transient Service (new every time)
public class TransientService
{
public Guid Id { get; } = Guid.NewGuid();
}
🔹 2. Register in Program.cs
builder.Services.AddSingleton<SingletonService>();
builder.Services.AddScoped<ScopedService>();
builder.Services.AddTransient<TransientService>();
🔹 3. Use Them in Middleware
⚠️ Important Rule
- ❌ Don’t inject Scoped directly in constructor
-
✅ Use it inside
Invoke()method
✅ Custom Middleware Example
public class LifetimeMiddleware
{
private readonly RequestDelegate _next;
private readonly SingletonService _singleton;
private readonly TransientService _transient;
public LifetimeMiddleware(RequestDelegate next,
SingletonService singleton,
TransientService transient)
{
_next = next;
_singleton = singleton;
_transient = transient;
}
public async Task Invoke(HttpContext context, ScopedService scoped)
{
await context.Response.WriteAsync($"Singleton: {_singleton.Id}\n");
await context.Response.WriteAsync($"Scoped: {scoped.Id}\n");
await context.Response.WriteAsync($"Transient: {_transient.Id}\n");
await _next(context);
}
}
🔹 4. Register Middleware
app.UseMiddleware<LifetimeMiddleware>();
🔥 Output Behavior (Very Important)
👉 If you refresh the page:
| Service Type | Behavior |
|---|---|
| Singleton | Same ID every time |
| Scoped | New ID per request |
| Transient | New ID every time (even inside same request if injected again) |
💡 Interview Explanation (Short)
- Singleton → One instance for entire app
- Scoped → One instance per HTTP request
- Transient → New instance every time requested
- Middleware can use all three, but Scoped must be injected in Invoke()

0 Comments
POST Answer of Questions and ASK to Doubt