Sub topic 7
The service locator pattern
This chapter explains the service locator pattern: what it is, how it differs from constructor injection, and what it costs. The next chapter shows the pattern through the get_it package. It assumes you know Dart classes and abstract classes, Future and async/await, and the constructor injection and composition root ideas from earlier chapters.
What a service locator is
A service locator is a central registry. At startup, you register how to build each dependency. Later, any code can ask the registry for a dependency by its type.
Constructor injection pushes dependencies in from outside. A service locator makes the consumer pull them. The consumer asks for what it needs at the moment it needs it.
| Aspect | Constructor injection | Service locator |
|---|---|---|
| Direction | Dependencies are pushed in | Dependencies are pulled out |
| Where dependencies are visible | In the constructor signature | Inside method or constructor bodies |
| Who must know about the container | Only the composition root | Every class that pulls |
| Missing dependency | Compile-time error | Runtime error |
Both patterns can use the same abstractions and the same composition root. The difference is how a class receives its collaborators.
A minimal locator
A locator needs only a map from a type to a function that builds that type. This version is small enough to read in full, and it runs with plain dart run.
class ServiceLocator {
final Map<Type, Object Function()> _factories = {};
void register<T extends Object>(T Function() factory) {
_factories[T] = factory;
}
T get<T extends Object>() {
final factory = _factories[T];
if (factory == null) {
throw StateError('No registration for $T. Call register<$T>() first.');
}
return factory() as T;
}
}
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}
class ProfileViewModel {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
}
}
final locator = ServiceLocator();
void setupLocator() {
locator.register<UserRepository>(() => ApiUserRepository());
locator.register<ProfileViewModel>(
() => ProfileViewModel(locator.get<UserRepository>()),
);
}
Future<void> main() async {
setupLocator();
final viewModel = locator.get<ProfileViewModel>();
await viewModel.load(1);
print(viewModel.name); // User 1
}Three details matter here.
- Registration uses the abstract type.
register<UserRepository>stores the factory underUserRepository, notApiUserRepository. Callers ask for the abstraction and never name the concrete class. - The registration code is the composition root.
setupLocatoris the one place that namesApiUserRepository. It is the same wiring you wrote in earlier chapters, in a different shape. ProfileViewModelstill takes its repository through its constructor. The locator is used only insetupLocator, so the view model has no idea a locator exists. This is the safest way to use one.
The map key is the generic type T you pass, not the runtime type of the object. If you write locator.register(() => ApiUserRepository()) without a type argument, Dart infers T as ApiUserRepository and the registration is stored under the concrete type. A later get<UserRepository>() then fails. Always write the type argument on register.
How the flow works
The locator separates two moments. Registration happens once, early. Lookup happens many times, later.
The registry is global. That is both the convenience and the main risk of the pattern.
Two ways to use a locator
You can use the locator in two very different ways. The first keeps the benefits of constructor injection. The second hides dependencies. Add the following to the same file to compare them.
// Style A: the locator is used only at the edge.
// The class declares what it needs in its constructor.
class ProfileViewModelA {
ProfileViewModelA(this._repository);
final UserRepository _repository;
Future<String> title(int id) async => 'Hello, ${await _repository.fetchName(id)}';
}
// Style B: the class pulls its own dependency.
// Nothing in the signature says it needs a UserRepository.
class ProfileViewModelB {
final UserRepository _repository = locator.get<UserRepository>();
Future<String> title(int id) async => 'Hello, ${await _repository.fetchName(id)}';
}In style A, setupLocator calls ProfileViewModelA(locator.get<UserRepository>()). A test can write ProfileViewModelA(FakeUserRepository()) and never touch the locator.
In style B, the dependency is hidden. To construct ProfileViewModelB, a test must first register a fake in the global locator. If the test forgets, the constructor throws a StateError. The class's public API gives no warning about this.
Costs of the pattern
Service locators have real downsides, and most are about style B.
Hidden dependencies
A constructor signature documents what a class needs. When classes call locator.get inside their bodies, you must read the entire implementation to learn their dependencies. Refactoring becomes harder, because the compiler cannot tell you which classes use a type you are about to change.
Runtime failures
A forgotten registration is not a compile error. It surfaces when the line executes, which might be deep in a rarely visited screen. Two habits reduce this risk:
- Call
setupLocator()first inmain, beforerunApp. - Write one test that calls
setupLocator()and then resolves every registered type, so a broken wiring fails in CI.
Global mutable state
The locator is usually a top-level variable. Tests that register fakes change that shared state, and a fake from one test can leak into the next. Reset the registry in a setUp or tearDown function. A locator without a reset method is hard to test, so add one if you write your own.
Coupling to the locator
Any class that calls locator.get depends on the locator itself. You cannot reuse that class in another project without bringing the locator along. Style A avoids this, because only the composition root depends on the locator.
Benefits of the pattern
The pattern persists because it solves real problems.
- No dependency on
BuildContext. Provider reads dependencies through the widget tree, so a class outside the tree (a background task, a plain Dart service, a navigation helper) cannot use it directly. A locator works anywhere in the Dart program. - Less boilerplate. You avoid threading a repository through five widget constructors to reach the one that needs it.
- Simple lifetime control. One registration decides whether the app shares one instance or creates a new one for each request. The chapter on lifetimes covers this.
- Easy to migrate to. Moving an app off hard-coded
ApiUserRepository()calls onto a locator is a small, mechanical change.
Swapping registrations in tests
Because the registry is a map, a test replaces a dependency by registering a different factory under the same type. A later registration overwrites the earlier one.
import 'package:test/test.dart';
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
void main() {
setUp(() {
setupLocator();
locator.register<UserRepository>(() => FakeUserRepository());
});
test('view model uses the fake repository', () async {
final viewModel = locator.get<ProfileViewModel>();
await viewModel.load(1);
expect(viewModel.name, 'Test User');
});
}This works because ProfileViewModel's factory calls locator.get<UserRepository>() when it is invoked, not when it is registered. It therefore sees the fake. In this simple locator, every get builds a new instance, so there is no cached object that could still hold the real repository. Once you add shared instances with caching, re-registering after the first lookup can leave stale objects behind. Real locator packages therefore provide an explicit reset operation.
For classes written in style A, you can skip the locator in tests entirely and pass the fake to the constructor. Prefer that when you can.
Service locator versus dependency injection
Some developers say the service locator is not dependency injection but an alternative to it. The distinction is useful:
- With injection, the class declares needs and receives them.
- With a locator, the class reaches out and fetches them.
In Flutter, the line is blurry. Provider.of<T>(context) is also a pull-based lookup, except the registry is the widget tree instead of a global variable. The tree gives you scoping for free and ties lookup to BuildContext. A global locator gives you access everywhere and has no built-in scoping.
Guidelines
- Register abstractions, and name the type argument explicitly.
- Resolve dependencies in the composition root and pass them to constructors (style A).
- Call
locator.getinside widgets only at the edge. A screen can resolve its view model once, for example ininitState, instead of scattering lookups throughbuild. - Add a test that resolves every registered type.
- Provide a way to reset the registry between tests.
Summary
A service locator is a global registry where you register builders at startup and look dependencies up by type later. It works well as the mechanism behind a composition root. It works poorly when classes pull their own dependencies, because that hides what they need and moves wiring errors to runtime. Keep constructors honest, and use the locator at the edges. The next chapter applies these ideas with the get_it package.
Exercise
A teammate writes class CartViewModel { final PaymentService _payments = locator.get<PaymentService>(); }. Name two problems this causes, and show how to change the class so it can be tested without registering anything in the locator.
Show answer
First, the dependency is hidden: the constructor does not show that CartViewModel needs a PaymentService, so the class can't be understood from its signature. Second, constructing it fails at runtime with a StateError if PaymentService was never registered, and tests must modify global state. Fix: take the dependency through the constructor, CartViewModel(this._payments); with final PaymentService _payments;, and resolve it only in the composition root, for example locator.register<CartViewModel>(() => CartViewModel(locator.get<PaymentService>()));. A test then calls CartViewModel(FakePaymentService()) directly.
Exercise
You call locator.register(() => ApiUserRepository()); with no type argument. Later locator.get<UserRepository>() throws. Why, and what is the fix?
Show answer
Dart infers T as ApiUserRepository from the factory's return type, so the registration is stored under that concrete type, and no entry exists for UserRepository. Write the type argument explicitly: locator.register<UserRepository>(() => ApiUserRepository());.