get_it and dependency injection
get_it is a service locator: you register objects in a global registry, and code asks the registry for what it needs. Spring for Dart is a dependency injection container: a class lists what it needs in its constructor, and the container finds the classes, builds them in the right order and passes them in.
Each section below does one task both ways. The idea behind the Spring side is explained in Inversion of control and dependency injection.
Registering and resolving
get_it. Every service is registered by hand, usually in one setup function that main calls first.
final getIt = GetIt.instance;
void setup() {
getIt.registerSingleton<Clock>(SystemClock());
getIt.registerSingleton<Mailer>(SmtpMailer());
}
void main() {
setup();
final mailer = getIt<Mailer>(); // or getIt.get<Mailer>()
mailer.send('[email protected]', 'Hello');
}
Spring for Dart. A class marked @Service() (or @Component()) is a bean. There is no setup function: the generator finds the classes at build time.
@Service()
class SystemClock implements Clock { /* ... */ }
@Service()
class SmtpMailer implements Mailer { /* ... */ }
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
What changes: the list of registrations disappears, and so does the risk of forgetting one. In exchange you run dart run build_runner build after you add or change annotations, and the container starts from a generated file (main.spring.dart).
A service with three dependencies
get_it. The order of registration matters, and the setup function repeats every constructor argument.
void setup() {
getIt.registerSingleton<Clock>(SystemClock());
getIt.registerSingleton<PurchaseRepository>(SqlPurchaseRepository());
getIt.registerSingleton<Mailer>(SmtpMailer());
getIt.registerSingleton<Checkout>(
Checkout(getIt<PurchaseRepository>(), getIt<Mailer>(), getIt<Clock>()),
);
}
Classes can also call getIt<Mailer>() inside their methods. Then the constructor no longer shows the dependencies, and a test has to fill the global registry before it can create the class.
Spring for Dart. The constructor is the whole declaration.
@Service()
class Checkout {
Checkout(this.purchases, this.mailer, this.clock);
final PurchaseRepository purchases;
final Mailer mailer;
final Clock clock;
}
What changes: adding a fourth dependency is one constructor parameter, with no setup code to edit. The container works out the order, and a missing or ambiguous dependency stops the start with a message that names the class and the parameter. Checkout stays a plain class: a unit test calls Checkout(fakeRepo, fakeMailer, fixedClock) without any container.
Lazy singletons and factories
get_it. registerLazySingleton creates the object on the first get; registerFactory creates a new one on every get.
getIt.registerLazySingleton<ReportGenerator>(() => ReportGenerator());
getIt.registerFactory<ShoppingCart>(() => ShoppingCart());
Spring for Dart. @Lazy() creates the bean on first use; @Scope(ScopeType.prototype) creates a new one for every injection and lookup.
@Component()
@Lazy()
class ReportGenerator { /* ... */ }
@Component()
@Scope(ScopeType.prototype)
class ShoppingCart {
final items = <String>[];
}
What changes: little. One difference: a lazy bean is still checked at startup (it must exist and be unique), so a typo fails at once rather than when the screen that needs it opens. @Lazy() on a constructor parameter also injects a proxy that finds the bean on first call, which breaks dependency cycles. See @Lazy.
Async initialization
get_it. registerSingletonAsync takes an async factory, dependsOn orders the async steps, and allReady() waits for all of them.
getIt.registerSingletonAsync<Database>(() => Database.open('shop.db'));
getIt.registerSingletonWithDependencies<PurchaseRepository>(
() => SqlPurchaseRepository(getIt<Database>()),
dependsOn: [Database],
);
Future<void> main() async {
await getIt.allReady();
runApp(const ShopApp());
}
Spring for Dart. A @PostConstruct() method may return a Future. runApplicationAsync waits for all of them before the application counts as started.
@Component()
class Database {
late final Connection connection;
@PostConstruct()
Future<void> open() async => connection = await Connection.open('shop.db');
}
@SpringBootApplication()
Future<void> main(List<String> args) => runApplicationAsync(args);
What changes: the async step lives in the class that needs it, not in the setup function. A trade-off to know: async init callbacks run side by side and are all awaited before the start completes, but they are not ordered among themselves. A bean receives Database while open() may still be running, so it must not use the connection in its own constructor or @PostConstruct. get_it's dependsOn gives you that order explicitly. See @PostConstruct.
Swapping an implementation per environment
get_it. An if in the setup function decides.
void setup({required bool production}) {
if (production) {
getIt.registerSingleton<Mailer>(SmtpMailer());
} else {
getIt.registerSingleton<Mailer>(LogMailer());
}
}
Spring for Dart. Each implementation says when it applies. The active profile comes from spring.profiles.active in a file, an environment variable or the command line.
@Component()
@Profile(['dev', 'test'])
class LogMailer implements Mailer { /* ... */ }
@Component()
@Profile(['!dev & !test'])
class SmtpMailer implements Mailer { /* ... */ }
When both implementations should exist and one is the usual choice, mark it @Primary() instead; the other is injected where a @Qualifier asks for it.
What changes: no branch in the startup code, and a third implementation is a third class. See @Profile and @Primary.
Swapping an implementation in tests
get_it. Reset the registry and register fakes before each test. allowReassignment lets a test replace one registration on top of the real setup.
setUp(() async {
await getIt.reset();
setup();
getIt.allowReassignment = true;
getIt.registerSingleton<PaymentGateway>(FakeGateway());
});
test('checkout pays', () {
getIt<Checkout>().pay(10);
// ...
});
The order matters: Checkout was built in setup() with the real gateway, unless it is registered lazily or reads the gateway through getIt at call time.
Spring for Dart. spring_boot_starter_test starts the real application with one bean replaced. The original is removed before any bean is created, so every bean that injects it gets the fake.
void main() {
final gateway = FakeGateway();
final app = springBootTest(
springApplication,
profiles: ['test'],
overrides: [BeanOverride<PaymentGateway>(gateway)],
);
test('checkout pays', () {
app.getBean<Checkout>().pay(10);
expect(gateway.charged, [10]);
});
}
What changes: the test also checks that the configuration binds and the beans find each other. The cost is a slower test than a plain unit test, and a build step before dart test. See BeanOverride and @TestBean.
Scopes
get_it. pushNewScope puts a layer on top of the registry. Registrations in it hide the ones below until popScope. A typical use is the time a user is logged in.
void onLogin(User user) {
getIt.pushNewScope(
scopeName: 'session',
init: (getIt) => getIt.registerSingleton<Session>(Session(user)),
);
}
Future<void> onLogout() => getIt.popScope();
Spring for Dart. A custom scope gives one instance per span you define. With a scoped proxy, a singleton that injects the bean always reaches the current instance.
@Component()
@Scope('session', proxyMode: ScopedProxyMode.targetClass)
class Session {
User? user;
}
// Registers the scope before any bean is created.
@Component()
class SessionScope implements BeanFactoryPostProcessor {
final scope = SimpleMapScope(conversationId: 'session');
@override
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) =>
beanFactory.registerScope('session', scope);
// @PreDestroy of Session runs; the next use gets a fresh Session.
void logout() => scope.destroy();
}
What changes: the two do not map one to one. get_it's scopes can replace any registration at run time, which is simple and flexible. Spring's scopes fix at build time which beans live in which scope, and singletons keep working through the proxy. Changing the whole set of beans at run time is not something Spring for Dart does; profiles decide it at startup. See @Scope.
In short
| Task | get_it | Spring for Dart |
|---|---|---|
| Register | registerSingleton, by hand, in order |
@Service() / @Component(), found at build time |
| Resolve | getIt<T>() anywhere |
constructor parameters; getBean<T>() outside beans |
| Three dependencies | each passed in the setup function | three constructor parameters |
| Lazy | registerLazySingleton |
@Lazy() |
| New instance each time | registerFactory |
@Scope(ScopeType.prototype) |
| Async init | registerSingletonAsync, dependsOn, allReady() |
Future @PostConstruct, runApplicationAsync (not ordered) |
| Per environment | if in setup |
@Profile, @Primary |
| Tests | reset(), allowReassignment |
BeanOverride, @TestBean |
| Scopes | pushNewScope / popScope at run time |
@Scope with a custom scope and a proxy |
| Missing dependency | an error at the first get |
the start fails, naming the class and parameter |
| Build step | none | build_runner after annotation changes |
get_it is the better choice for a small app with a handful of services, when you do not want a build step, or when you need to swap registrations freely at run time. Spring for Dart pays off when the graph grows, when configuration, profiles and tests should replace implementations without edits to setup code, or when you want the starters (web, Feign, cache, security) in the same container.