Small byte 2: what is a captive dependency?

I’m a big fan of DeveloperDeveloperDeveloper (DDD) events. I was lucky to attend DDD South West in 2018 before my son was born. Needless to say I’m very happy that the recordings of the 2020 conference are available on YouTube, and this has been my pastime in the morning when I’m getting Andre’s lunch ready for the day and doing other household chores.

What I have decided to do with these is to take notes of the terms or concepts I’m not very familiar with, research them, and then write posts about some of them.

The first talk I listened to was Steve Collin’s .NET DI Container Tips and Tricks. He mentioned the term “captive dependency” and I hadn’t heard of this concept before.

So, a captive dependency happens when there is a mismatch of dependency lifetimes. For example, when a dependency with Transient lifetime is injected into a Singleton, that will cause the Transient service to stale.

I have two services below:

I register them in the ConfigureServices method in Startup.cs like so:

and then inject them into a Controller:

Based on how the order number is created, you would expect the GetCode method in the TaxCodeCalculator, and consequently, the Get method of the OrdersController to return a different value everytime you call it, but because of the misconfigured lifetimes of dependencies, the value will always be the one which was generated when the first request was made. To fix it, we can change the Singleton to be Transient.