registerAsync<T, R extends T> static method

void registerAsync<T, R extends T>(
  1. SpotAsyncGetter<R> locator, {
  2. String? name,
})

Registers an async singleton with asynchronous initialization.

Use this for services that require async setup (database connections, API authentication, file loading, etc.). The instance is created once on first access and cached for subsequent requests.

Type Parameters:

  • T: The interface or base type to register
  • R: The concrete implementation (must extend or implement T)

Parameters:

  • locator: Async factory function called once to create the singleton. Use get parameter to resolve dependencies.
  • name: Optional name qualifier for named instances

Example:

// Database with async initialization
Spot.registerAsync<Database, AppDatabase>((get) async {
  final db = AppDatabase();
  await db.initialize();
  await db.runMigrations();
  return db;
});

// Named async singleton
Spot.registerAsync<Cache, RemoteCache>(
  (get) async => await RemoteCache.connect(),
  name: 'remote',
);

// API client with token refresh
Spot.registerAsync<IApiClient, ApiClient>((get) async {
  final client = ApiClient();
  await client.refreshTokens();
  return client;
});

// Resolve with spotAsync
final db = await spotAsync<Database>();

See also:

Implementation

static void registerAsync<T, R extends T>(SpotAsyncGetter<R> locator, {String? name}) {
  final key = SpotKey<T>(T, name);

  if (registry.containsKey(key) && logging) {
    log.w('Overriding async singleton: $key with $R');
  }

  registry[key] = SpotService<T>(
    SpotType.asyncSingleton,
    null,
    R,
    asyncLocator: locator as SpotAsyncGetter<T>,
  );

  if (logging) log.v('Registered async singleton $key -> $R');
}