ServiceLocator class

Lightweight service locator with lifecycle management.

Supports singleton, lazy-singleton, factory, scoped, and async-singleton lifetimes. Includes helpers for testing (reset) and grouped registration (registerModule).

Usage

// Bootstrap (e.g. in main()):
ServiceLocator.instance
  ..registerModule(NetworkModule())
  ..registerModule(AuthModule());

await ServiceLocator.instance.allReady();

// Resolve anywhere:
final auth = ServiceLocator.instance.get<AuthService>();

Constructors

ServiceLocator()
Creates a fresh, isolated ServiceLocator.

Properties

descriptors Map<Type, ServiceDescriptor>
final
hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
singletons Map<Type, Object>
final

Methods

allReady() Future<void>
Waits for all async singletons registered with registerSingletonAsync to resolve.
disposeAll() Future<void>
Calls PkDisposable.dispose on all singleton instances that implement it.
get<T extends Object>() → T
Resolves and returns the service registered for type T.
isRegistered<T extends Object>() bool
Returns true if a service is registered for type T.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
registerFactory<T extends Object>(T factory(ServiceLocator locator)) → void
Registers a factory for type T.
registerLazySingleton<T extends Object>(T factory(ServiceLocator locator)) → void
Registers a lazy singleton for type T.
registerModule(DiModule module) → void
Registers all services declared by module.
registerScoped<T extends Object>(T factory(ServiceLocator locator)) → void
Registers a scoped factory for type T.
registerSingleton<T extends Object>(T instance) → void
Registers a pre-built instance as a singleton for type T.
registerSingletonAsync<T extends Object>(Future<T> factory(ServiceLocator locator)) → void
Registers an async singleton for type T.
reset() → void
Clears all registrations and cached instances.
toString() String
A string representation of this object.
inherited
tryGet<T extends Object>() → T?
Resolves the service registered for type T, or returns null if not registered.

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Properties

instance ServiceLocator
The default global ServiceLocator.
no setter