Skip to content
Katabench
Try free

Retire the Service Locator

Medium About 20 min Free, no account needed

A quote calculator fetches its rate table from a global ServiceLocator, so its one real dependency is invisible in every signature. Replace the locator with constructor injection. Caching the located table into a readonly field keeps the calculator quietly coupled to the global and leaves the key rule red.

The brief

Quotes.QuoteCalculator prices a shipment: rate per kilogram times weight. Simple, except for where the rates come from. The calculator reaches into ServiceLocator.Rates, a public static field anyone can read and anyone can swap at runtime. Its constructor takes nothing, so its signature promises "no dependencies" while Cost quietly depends on global state. A test that forgets to plant the right table into the locator fails mysteriously; two tests that plant different tables cannot run in parallel; and no caller can tell, without reading the body, that this class needs rates at all. A service locator does not remove dependencies. It hides them.

The trap

The tidy-looking half-fix is to fetch once and cache:

C#
private readonly IRateTable _rates = ServiceLocator.Rates;

The field is readonly, the field is abstract-typed, and the readonly rule is satisfied. But the calculator still names ServiceLocator, so the "no locator" rule stays red, and the hidden coupling is fully intact: construction order now silently matters, and the constructor still tells callers nothing. Moving the grab from the method to the field initializer moves the smell, not the dependency.

Your job

Make the dependency visible and let the locator die. QuoteCalculator takes an IRateTable through its constructor, stores it in a readonly field, and is sealed. The composition root (the Solution class) creates StandardRates and passes it in. With no remaining callers, delete ServiceLocator outright; a retired global should not stay behind as an attractive nuisance. Every quote must come out unchanged.

How it's graded

Your submission must (1) still pass the behavior tests (identical costs) and (2) satisfy every rule shown in the results: the calculator references IRateTable but never ServiceLocator, it owns its table in a readonly field, and it is sealed. The cache-it-in-a-field trap satisfies the readonly rule and leaves the no-locator rule red; only real constructor injection turns everything green.

A dependency you cannot see in the constructor is still a dependency. It has just been moved somewhere the compiler, the caller, and the test runner cannot help you with it.

How it is graded

Executable structural checks grade the shape of your types as well as their behavior.

SOLID principles exercises →

Related guides

What it practices

Dependency injection
Ask for collaborators through constructors instead of newing them up or locating them.

Related katas