putIfAbsent<T> static method

T putIfAbsent<T>(
  1. T builder(), {
  2. String? tag,
})

Registers a dependency only if it doesn't already exist.

If a dependency with the same type and tag exists, returns the existing instance. Otherwise, creates and registers a new instance using builder.

Parameters:

  • builder: Function that creates the dependency if needed
  • tag: Optional identifier for multiple instances

Returns either the existing or newly created instance.

Example:

// First call creates the instance
final service1 = Dependency.putIfAbsent<DataService>(
  () => DataService(),
);

// Second call returns the same instance
final service2 = Dependency.putIfAbsent<DataService>(
  () => DataService(),
);

print(identical(service1, service2)); // true

Implementation

static T putIfAbsent<T>(
  T Function() builder, {
  String? tag,
}) {
  final key = _getKey(T, tag: tag);

  if (_dependencyStore[key] != null) {
    return _dependencyStore[key];
  }

  final dependency = builder();
  _dependencyStore[key] = dependency;
  return dependency;
}