Bald Bearded Builder
aspnetcore/dont-make-this-dependency-injection-mistake

Don't Make This Dependency Injection Mistake!

Injecting a shorter-lived service into a longer-lived one effectively extends the dependency's lifetime and creates invalid service designs.

Loads from YouTube when you press play

Transcript 1 topic

Choose service lifetimes

0:00

Okay, you're deciding what scopes to use when you're registering your services. Now this is more of a design topic than a practical code topic and you'll see why a little later. But let's imagine we have two services. Now we'll register each as their name implies. So subscriber singleton service will be a singleton and like and comment scope service will be a scope service.

Next, we'll update that subscriber singleton service to receive a like and comment scope service into its constructor. Now this is bad juju. Why? Because a singleton services lifecycle is the entire application's lifecycle, whereas a scoped service has a lifecycle of the request or a unit of work. That means if we inject a service into another service that has a longer life cycle, we're essentially upsizing the life cycle of the injected service.

So when the application starts and it spins up that subscriber singleton service, it's injecting in a like and comment scope service with no user information. There is no request. And the really bad part of this is when a request actually comes in, we try to use that singleton service, well, that like and comment scope service still doesn't have a user. That thing was instantiated before a request ever existed. So why is this more of a design topic than a practical code topic?

Because Microsoft thought of this already. They actually blocked that behavior at build time. Now when I try to compile this code, they're gonna give me an invalid operation exception, basically telling me that hey I can't consume scoped or transient services in this singleton service. In fact the same error would occur if you tried to inject a transient service into a scoped or singleton.

So it's interesting your code will allow you to write that and not give you any of the red squigglies, but the compile time will stop you. So just keep that in mind when you're designing those services and their lifecycles so you don't catch yourself having to go back and refactor code that you thought was going to be okay.

Sign in to join in. Reading needs nothing.