Froodooo
Froodooo

Reputation: 177

Lifetime in chained Dependency Injection

In .NET Core, there are three different lifetimes one can use: Transient, Scoped and Singleton.

Let's assume I have the following chain of depencency-injected services:

Service A > Service B > Service C,

meaning that Service A has Service B injected (e.g. Service A depends on Service B) and Service B has Service C injected.

Now consider Service B having a Singleton lifetime, and Service C having a Transient lifetime. Because Service B is a Singleton, it is only created once. Service C is Transient, but because Service B is a Singleton, Service C is still just created once as well.

Is this argumentation correct, and thus does the Transient lifetime I set for Service C not make sense? Or am I thinking wrongly here?

Upvotes: 1

Views: 650

Answers (1)

Steven
Steven

Reputation: 172606

What you are describing here is a common problem known as Captive Dependency. Service C becomes captive because its consumer has a longer lifetime.

This issue is widespread and is a common source of bugs in applications that use Dependency Injection and DI containers. When an application grows, these issues can easily slip in undetected. From experience I can tell that tracing back a bug to such misconfiguration can take a lot of time.

Unfortunately, the built-in container of .NET Core does not detect and prevent these kinds of mistakes. Some of the other, more mature, DI libraries for .NET actually have these kinds of features where they detect and prevent these kinds of misconfigurations.

Upvotes: 2

Related Questions