putLazy<T> method

void putLazy<T>(
  1. T factory(), {
  2. String? tag,
  3. bool isPermanent = false,
  4. bool alwaysNew = false,
})

Register a lazy factory

  • Set isPermanent to true for permanent singletons (survive scope cleanup)
  • Set isPermanent to false for temporary singletons (cleaned up with scope)
  • Set alwaysNew to true to create fresh instance on each find() call

Note: Cannot set both isPermanent and alwaysNew to true

Implementation

void putLazy<T>(
  T Function() factory, {
  String? tag,
  bool isPermanent = false,
  bool alwaysNew = false,
}) {
  if (_disposed) {
    throw Exception('Cannot register in a disposed scope: $name');
  }

  if (isPermanent && alwaysNew) {
    throw ArgumentError('Cannot set both isPermanent and alwaysNew to true. '
        'A factory that creates new instances cannot be permanent.');
  }

  final key = _makeKey<T>(tag);
  final trackingKey = _getDependencyKey(T, tag);

  // Store the factory for later use
  _factories[key] = factory;

  // Set the use count based on behavior
  // -1 = permanent singleton
  // 0 = temporary singleton
  // -2 = factory (always creates new)
  _useCount[trackingKey] = alwaysNew ? -2 : (isPermanent ? -1 : 0);

  final behavior = alwaysNew
      ? 'factory (always new)'
      : (isPermanent ? 'permanent singleton' : 'temporary singleton');

  ZenLogger.logDebug(
      'Registered lazy $behavior for $T${tag != null ? ' with tag $tag' : ''}');
}