registerSingle<T, R extends T> static method
Registers a singleton that returns the same instance on each resolution.
Singletons are initialized lazily on first access and cached for subsequent requests. Perfect for shared state, services, and managers.
Type Parameters:
T: The interface or base type to registerR: The concrete implementation (must extend or implementT)
Parameters:
locator: Factory function called once to create the singleton. Usegetparameter to resolve dependencies.name: Optional name qualifier for named instances
Example:
// Simple singleton
Spot.registerSingle<ISettings, Settings>(
(get) => Settings(),
);
// Named singleton
Spot.registerSingle<Database, ProductionDatabase>(
(get) => ProductionDatabase(),
name: 'production',
);
// Singleton with dependencies
Spot.registerSingle<IAuthService, AuthService>(
(get) => AuthService(
apiClient: get<IApiClient>(),
storage: get<IStorage>(),
),
);
See also:
- registerFactory for factory registration
- registerAsync for async singleton registration
- dispose to reset and recreate singletons
Implementation
static void registerSingle<T, R extends T>(SpotGetter<R> locator, {String? name}) {
final key = SpotKey<T>(T, name);
if (registry.containsKey(key) && logging) {
log.w('Overriding single: $key with $R');
}
registry[key] = SpotService<T>(SpotType.singleton, locator as SpotGetter<T>, R);
if (logging) log.v('Registered singleton $key -> $R');
}