put<S> method

S put<S>(
  1. S builder(), {
  2. String? tag,
  3. bool permanent = false,
})

Immediately instantiates and registers a dependency.

The builder is called immediately. If a dependency of type S with the same tag already exists, it is replaced (disposed) before the new one is created.

// Example usage:

scope.put(() => AuthService());

Use permanent to survive a non-forced reset only. dispose always resets with force: true, so permanents do not leak across disposed scopes. Prefer permanent on root / long-lived scopes.

Returns the created instance.

Implementation

S put<S>(S Function() builder, {String? tag, bool permanent = false}) {
  _ensureUsable();
  final key = _getKey<S>(tag);
  final keyString = key.debugString;

  if (_registry.containsKey(key) || _aliases.containsKey(key)) {
    throw StateError(
      'LevitScope($name): "$keyString" is already registered. '
      'Await delete<$S>(tag: ${tag == null ? 'null' : "'$tag'"}, force: true) '
      'before registering a replacement.',
    );
  }

  final info = LevitDependency<S>(permanent: permanent);

  // Instance creation happens before registration so middleware sees final metadata.
  info.instance = _createInstance<S>(builder, keyString, info);

  _registerBinding(key, keyString, info, 'put', tag: tag);

  _initializeInstance(info.instance, keyString, info);

  return info.instance as S;
}