clearAll method

void clearAll({
  1. bool force = false,
})

Clear all dependencies from this scope

Implementation

void clearAll({bool force = false}) {
  if (_disposed) {
    return;
  }

  // Clear type bindings
  final typeInstances = Map<Type, dynamic>.from(_typeBindings);
  for (final entry in typeInstances.entries) {
    final type = entry.key;
    final instance = entry.value;

    // Check permanence
    final key = _getDependencyKey(type, null);
    final isPermanent = _useCount[key] == -1;

    if (!isPermanent || force) {
      _typeBindings.remove(type);
      _useCount.remove(key);

      if (instance is ZenController && !instance.isDisposed) {
        try {
          instance.dispose();
        } catch (e) {
          ZenLogger.logError(
              'Error disposing controller during clearAll: $e');
        }
      }
    }
  }

  // Clear tagged bindings using their registered generic Type
  final registeredTypes = List<Type>.from(_taggedBindings.keys);
  for (final registeredType in registeredTypes) {
    final tagMap = _taggedBindings[registeredType];
    if (tagMap == null) continue;

    final entries = Map<String, dynamic>.from(tagMap);
    for (final entry in entries.entries) {
      final tag = entry.key;
      final instance = entry.value;

      final key = _getDependencyKey(registeredType, tag);
      final isPermanent = _useCount[key] == -1;

      if (!isPermanent || force) {
        tagMap.remove(tag);
        _useCount.remove(key);

        if (instance is ZenController && !instance.isDisposed) {
          try {
            instance.dispose();
          } catch (e) {
            ZenLogger.logError(
                'Error disposing controller during clearAll: $e');
          }
        }
      }
    }

    if (tagMap.isEmpty) {
      _taggedBindings.remove(registeredType);
    }
  }

  // Clear factories using each factory's exact tracking key
  if (force) {
    for (final entry in _factories.values) {
      _useCount.remove(entry.trackingKey);
    }
    _factories.clear();
  } else {
    final factoriesToRemove = <String>[];
    for (final entry in _factories.entries) {
      final isPermanent = _useCount[entry.value.trackingKey] == -1;
      if (!isPermanent) {
        factoriesToRemove.add(entry.key);
        _useCount.remove(entry.value.trackingKey);
      }
    }

    for (final key in factoriesToRemove) {
      _factories.remove(key);
    }
  }

  ZenLogger.logDebug('Cleared all dependencies from scope: $name');
}