Member-only story

How to Inject a Scoped Service into .NET Middleware (And Do It the Right Way)

Arshak Ahamed
3 min readNov 15, 2024

--

Flow diagram showing how to inject a scoped service into .NET middleware using IServiceScopeFactory, ensuring proper lifetime management.

Let’s face it — middleware is one of those things in .NET that can trip you up if you’re not careful. Especially when you’re dealing with scoped services. Ever tried injecting a scoped service directly into middleware? If you have, you probably ran into the dreaded lifetime mismatch error. Been there, done that.

But don’t worry, I’ve got you covered. In this post, I’ll walk you through how to inject a scoped service into middleware safely, using a practical example. Trust me, once you understand the trick, it’s smooth sailing.

Why Can’t You Just Inject a Scoped Service into Middleware?

Here’s the problem: Middleware in .NET is registered as a singleton. This means it’s created once and hangs around for the entire lifetime of the application. Scoped services, on the other hand, are created for each request. If you try to inject a scoped service directly into middleware via the constructor, .NET won’t let you — it’s like trying to fit a square peg into a round hole.

So, what’s the solution? You need to create a scope inside the middleware itself. That way, the scoped service stays tied to the current request.

--

--

Arshak Ahamed
Arshak Ahamed

Written by Arshak Ahamed

Lead Software Engineer (Full Stack) & Tech enthusiastic

No responses yet

Write a response