register<T> method

void register<T>(
  1. ZenithKey<T> key,
  2. T factory(), {
  3. ZenithLifetime lifetime = ZenithLifetime.scoped,
})

Registers key with a factory in the container, tagging it with lifetime for Captive Dependency Guard enforcement.

If lifetime is ZenithLifetime.singleton, the factory must not try to resolve any ZenithLifetime.scoped key from this container — doing so throws ZenithCaptiveDependencyException immediately.

Implementation

void register<T>(
  ZenithKey<T> key,
  T Function() factory, {
  ZenithLifetime lifetime = ZenithLifetime.scoped,
}) {
  if (_isDisposed || _isClosing) {
    throw StateError('Cannot register in a disposed ZenithTenantScope');
  }

  if (lifetime == ZenithLifetime.scoped) {
    _scopedKeys.add(key);
    container.getOrCreate<T>(key, (_) => factory());
  } else {
    // Singleton registration: wrap factory to detect captive dependencies.
    container.getOrCreate<T>(key, (_) {
      return _CaptiveGuard.runSingleton(factory);
    });
  }
}