Singleton and Dependency Injection
In short: Singleton guarantees a single instance of a class, while Dependency Injection passes dependencies in from outside, so the code can be tested with a substitute, such as a clock.
Problem
The test that passes only on Fridays
On Fridays the shop gives a 10% discount. The program has one clock, so it is a Singleton: a class with only one object, reachable from anywhere. The order service asks it what day it is:
class SystemClock{ public static readonly SystemClock Instance = new SystemClock();
private SystemClock() { }
public DateTime Today => DateTime.Today;}
class OrderService{ public decimal Price(decimal amount) { if (SystemClock.Instance.Today.DayOfWeek == DayOfWeek.Friday) { return amount * 0.9m; } return amount; }}Someone writes a test to make sure the discount works:
var service = new OrderService();Console.WriteLine($"Friday discount: expected €90.00, got €{service.Price(100):F2}");Run on Monday, October 26, 2026, the test prints:
Friday discount: expected €90.00, got €100.00On a Friday the same test prints 90.00. The test passes one day a week and fails on the other six, and the code is the same. To check the discount you have to wait for Friday or move the computer's clock.
The clock itself is done right. The problem is that Price reaches for it itself. From outside you can't see that the service depends on a clock: new OrderService() asks for nothing. The test can't give it another day, because it can't give it anything.
The idea
The one object and handing it in
A Singleton guarantees two things: there is only one object, and anyone can take it from anywhere. The first is sometimes needed. The second is the price:
- a hidden dependency. Who uses the clock shows only if you read every line of every method;
- shared state. Whatever one piece of code changes in the object, everyone else sees, including the next test;
- it can't be swapped. The code points to the concrete class by name. Another clock for the test has no way in.
The fix is not to remove the clock, but to hand it in from outside. The service doesn't look for its dependency, it receives it in the constructor. Which clock it is, is decided by whoever creates the service: the program hands in the real one, and the test its own, with a date the test picks.
This is called Dependency Injection (DI). There are three roles:
- the service says what it needs: a parameter of an interface type in the constructor;
- the dependency is the object it is given: the real clock or the test one;
- the wiring happens in one place, at the start of the program. That is where you decide which object goes where.
The Singleton can even stay: the one clock is handed in like any other object. Nobody just reaches for it on their own.
See it
Singleton, the way the language gives it
if (instance == null). If two threads reach the check at the same time, you get two objects. The language has safer ways.The clock from the problem is in a static readonly field. The runtime creates it once, before the class is used, and that is safe with many threads too. If creating it is expensive and should happen only on the first request, there is Lazy<T>: the object is made on the first .Value, also once:class SystemClock{ private static readonly Lazy<SystemClock> instance = new Lazy<SystemClock>(() => new SystemClock());
public static SystemClock Instance => instance.Value;
private SystemClock() { Console.WriteLine("Creating the clock"); }}Console.WriteLine("Start");var a = SystemClock.Instance;var b = SystemClock.Instance;Console.WriteLine(a == b);StartCreating the clockTrueMore precisely, if you are curious
static readonly and Lazy<T> protect only against a second creation. They don't protect against the hidden dependency: SystemClock.Instance can still be called from anywhere.See it
The clock comes in from outside
IClock: an interface with one property. SystemClock from the problem only adds : IClock:interface IClock{ DateTime Today { get; }}
class OrderService{ private readonly IClock clock;
public OrderService(IClock clock) { this.clock = clock; }
public decimal Price(decimal amount) { if (clock.Today.DayOfWeek == DayOfWeek.Friday) { return amount * 0.9m; } return amount; }}In the program, the real clock is handed in once, at creation:
var service = new OrderService(SystemClock.Instance);Now new OrderService(...) says out loud that it can't work without a clock. The dependency shows in the constructor's signature, not somewhere inside a method.
In ASP.NET Core the handing in is done by the framework's container. You register the clock once, builder.Services.AddSingleton<IClock>(SystemClock.Instance), and every controller that asks for an IClock in its constructor gets it. That is how IProductService works in the lessons MVC, Views with Razor and WebAPI. AddSingleton there means "one object for the whole application", but nobody takes it on their own: the framework hands it in.
See it
The test picks the day itself
The test needs a clock you can tell which date to return:
class FakeClock : IClock{ public DateTime Today { get; set; }
public FakeClock(DateTime today) { Today = today; }}The test hands it in instead of the real one:
var clock = new FakeClock(new DateTime(2026, 10, 30));var service = new OrderService(clock);Console.WriteLine($"Friday: €{service.Price(100):F2}");
clock.Today = new DateTime(2026, 10, 27);Console.WriteLine($"Tuesday: €{service.Price(100):F2}");Friday: €90.00Tuesday: €100.00var clock = new FakeClock(new DateTime(2026, 10, 30));var service = new OrderService(clock);Console.WriteLine($"Friday: €{service.Price(100):F2}");
clock.Today = new DateTime(2026, 10, 27);Console.WriteLine($"Tuesday: €{service.Price(100):F2}");Step by step, in words
- Before, Price reached for SystemClock.Instance itself: a hidden link to a global object the test cannot change.
- The test makes its own clock: a FakeClock that says 2026-10-30, a Friday.
- The clock comes in from outside, through the constructor. OrderService only keeps a reference to it.
- Price(100): the service asks its clock. It's a Friday, so the sum is 90.00.
- The test moves the date to 2026-10-27, a Tuesday. Nothing in OrderService changes.
- The same Price(100): a Tuesday, 100.00. The test gives these two numbers on any day of the week.
The test gives these two numbers on a Monday, on a Friday and on a Sunday. OrderService is the same class that runs in the shop: the test changes only what it hands in.
More precisely, if you are curious
TimeProvider with GetLocalNow(): the program hands in TimeProvider.System, and the tests their own subclass. The idea is the same as IClock.Try it
Predict the output
The classes are from the cards before this one. October 31, 2026 is a Saturday. What does the program print?
var clock = new FakeClock(new DateTime(2026, 10, 30));var shop = new OrderService(clock);clock.Today = new DateTime(2026, 10, 31);var app = new OrderService(clock);
Console.WriteLine($"€{shop.Price(50):F2}");Console.WriteLine($"€{app.Price(50):F2}");Try it
Find the bug
The cart is a Singleton, "so that there is one":
class Cart{ public static readonly Cart Instance = new Cart(); private readonly List<string> items = new List<string>();
private Cart() { }
public void Add(string item) { items.Add(item); }
public int Count => items.Count;}Two tests, each with its own checkout page. check prints OK or what the test expected:
var first = new CheckoutPage();first.Add("Coffee");first.Add("Mug");Check("Test 1", first.Count, 2);
var second = new CheckoutPage();second.Add("Coffee");Check("Test 2", second.Count, 1);Test 1: OKTest 2: FAIL, expected 1, got 3Each test passes on its own. Together, the second fails. Which line has the bug?
Pick the line with the bug.
The page takes the one cart itself. Both pages, and both tests, fill the same object: the second test sees the coffee and the mug of the first. In the shop it is even worse: all customers shop in one cart. A cart is not something there is one of in the program; there is one per customer. The fix: the cart is an ordinary class with a public constructor, and the page receives it in its own: new CheckoutPage(new Cart()). Each test makes its own cart, and both pass.
More precisely, if you are curious
Test libraries run tests in an order that is not guaranteed, sometimes at the same time. A test that passes only when it runs first is a test that fails at random. Shared state in a Singleton is the most common cause.
The idea
When you don't need it
A Singleton makes sense when a second copy would be a mistake and the object keeps nothing that changes: settings read once at startup, the log, the pool of database connections. Even then it is better handed in from outside than reached for by everyone.
Handing in from outside has a price too. It's not worth it when:
- the dependency never changes and doesn't get in the way of tests.
Math.Roundis not a dependency you hand in; - the program is small. Wiring by hand in Main is enough; a DI framework is for big applications;
- the constructor asks for eight dependencies. That's not a DI problem: the class does too much.
Exercise
Black Friday
Solve the task in your editor.
Black Friday. On November 27, 2026 the shop gives a 30% discount, and on other Fridays still 10%. Add the rule to OrderService and check it with FakeClock for three dates: Black Friday, October 30 (a Friday) and October 27 (a Tuesday). The test gives the same output on any day.
Black Friday: €70.00Friday: €90.00Tuesday: €100.00More tasks
- Order numbers. The counter for order numbers is a Singleton and starts at 1001. Make it a dependency of
OrderServiceand write two tests that both get 1001 as the first number. - A cart for every customer. Fix the bug from "Find the bug" all the way: the cart is not a Singleton, and every page gets its own. Two customers add different items, and each sees only their own.
- Night discount. Between 22:00 and 6:00 the discount is 5%. The clock now has to give the hour too. What do you change in IClock, and how many tests do you need to be sure?
Test
Check yourself
Related lessons
Section titled "Related lessons"- Builds on: Nested classes · Lambdas and delegates · Design patterns · Strategy
- Continues in: Adapter and Facade · Repository · The shop: which pattern where · SOLID without dogma
- Tasks on this topic: Design patterns