delete<T> method
Delete a dependency by type and optional tag
Implementation
bool delete<T>({String? tag, bool force = false}) {
if (_disposed) {
return false;
}
final key = _getDependencyKey(T, tag);
final factoryKey = _makeKey<T>(tag);
// Check if permanent for exact (T, tag)
if (_useCount.containsKey(key) && _useCount[key] == -1 && !force) {
ZenLogger.logWarning(
'Attempted to delete permanent dependency of type $T${tag != null ? ' with tag $tag' : ''}. Use force=true to override.');
return false;
}
// Check if we have a factory registered
if (_factories.containsKey(factoryKey)) {
_factories.remove(factoryKey);
_useCount.remove(key);
return true;
}
dynamic instanceToDelete;
dynamic trackingKeyToRemove = key;
if (tag != null) {
final exactMap = _taggedBindings[T];
if (exactMap != null && exactMap.containsKey(tag)) {
instanceToDelete = exactMap.remove(tag);
if (exactMap.isEmpty) {
_taggedBindings.remove(T);
}
} else {
// Fallback: match subtype registered under a concrete type with this tag
Type? matchedType;
for (final entry in _taggedBindings.entries) {
final candidate = entry.value[tag];
if (candidate != null && candidate is T) {
matchedType = entry.key;
instanceToDelete = candidate;
break;
}
}
if (matchedType == null) {
return false;
}
trackingKeyToRemove = _getDependencyKey(matchedType, tag);
if (_useCount[trackingKeyToRemove] == -1 && !force) {
ZenLogger.logWarning(
'Attempted to delete permanent dependency of type $matchedType with tag $tag. Use force=true to override.');
return false;
}
_taggedBindings[matchedType]?.remove(tag);
if (_taggedBindings[matchedType]?.isEmpty ?? false) {
_taggedBindings.remove(matchedType);
}
}
} else {
instanceToDelete = _typeBindings[T];
if (instanceToDelete == null) {
return false;
}
// Remove from type map
_typeBindings.remove(T);
}
// Remove from use count tracking
_useCount.remove(trackingKeyToRemove);
if (instanceToDelete is ZenController && !instanceToDelete.isDisposed) {
instanceToDelete.dispose();
}
ZenLogger.logDebug(
'Deleted dependency $T${tag != null ? ' with tag $tag' : ''}');
return true;
}