replaceInstance<T> method

  1. @visibleForTesting
  2. @override
void replaceInstance<T>(
  1. T instance, {
  2. String? key,
})
inherited

Replaces an instance record with a concrete instance.
This function should only be used for unit testing.
Any other use is discouraged.
When key is provided it will search the instance that have the same key

Implementation

@visibleForTesting
@override
void replaceInstance<T>(T instance, {String? key}) {
  uncommit();
  if (!isAdded<T>(key: key)) {
    addInstance<T>(instance, key: key);
  } else {
    final className = T.toString();

    final data = (key == null) ? layersGraph.getBindByClassName(this, className: className) : layersGraph.getBindByKey(this, bindKey: key);

    final injector = data!.key;

    final index = (key == null) ? injector.binds.indexWhere((bind) => bind.className == className) : injector.binds.indexWhere((bind) => bind.key == key);

    final newBind = Bind<T>(
      constructor: () => instance,
      type: BindType.instance,
      instance: instance,
      key: key,
    );

    injector.binds[index] = newBind;
  }

  commit();
}