put<T> method

T put<T>(
  1. T instance, {
  2. String? tag,
  3. bool? isPermanent,
})

Register a dependency in this scope.

ZenService instances default to isPermanent = true. All other types default to isPermanent = false.

Implementation

T put<T>(T instance, {String? tag, bool? isPermanent}) {
  if (_disposed) {
    throw ZenDisposedScopeException(
      scopeName: name ?? 'UnnamedScope',
      operation: 'put',
    );
  }

  // Auto-initialize ZenController instances (ZenService extends ZenController)
  if (instance is ZenController) {
    _initializeController(instance);
  }

  // Smart default: ZenService instances default to permanent=true
  final permanent = isPermanent ?? (instance is ZenService);

  if (tag != null) {
    final tagMap = _taggedBindings.putIfAbsent(T, () => <String, dynamic>{});

    // Check if we're replacing a dependency for this exact (T, tag) pair
    final oldInstance = tagMap[tag];
    if (oldInstance != null) {
      ZenLogger.logWarning(
          'Replacing existing dependency of type $T with tag: $tag');
      if (oldInstance is ZenController && !oldInstance.isDisposed) {
        oldInstance.dispose();
      }
    }

    // Store by registered type T and tag
    tagMap[tag] = instance;

    // Set initial use count keyed by registered type T
    final key = _getDependencyKey(T, tag);
    _useCount[key] = permanent ? -1 : 0;
  } else {
    // Check if we're replacing a dependency
    final oldInstance = _typeBindings[T];
    if (oldInstance != null) {
      ZenLogger.logWarning('Replacing existing dependency of type: $T');
      if (oldInstance is ZenController && !oldInstance.isDisposed) {
        oldInstance.dispose();
      }
    }

    // Store by type
    _typeBindings[T] = instance;

    // Set initial use count
    final key = _getDependencyKey(T, null);
    _useCount[key] = permanent ? -1 : 0;
  }

  ZenLogger.logDebug(
      'Registered $T${tag != null ? ' with tag $tag' : ''} (${permanent ? 'permanent' : 'temporary'})');

  return instance;
}