singleton<T> abstract method

void singleton<T>({
  1. String? name,
  2. required FactoryFunction<T> factory,
  3. bool eager = false,
})

Registers a singleton service.

The same instance is returned for all make calls within the same scope.

container.singleton<Database>(factory: (c, _) => Database.connect());
final db1 = container.make<Database>();
final db2 = container.make<Database>();
expect(identical(db1, db2), true);
  • eager: true → instance is created during initialize
  • eager: false (default) → lazy creation on first make

Throws ServiceContainerException.duplicateRegistration if already registered.

Implementation

void singleton<T>({
  String? name,
  required FactoryFunction<T> factory,
  bool eager = false,
});