tryInstance<T> method

Instance? tryInstance<T>({
  1. String? name,
  2. bool autoRegister = false,
})

Implementation

Instance? tryInstance<T>(
    {String? name,

    /// Will look for any already created instances that implement the provided type
    bool autoRegister = false}) {
  final typeName = '$T';
  // ignore: omit_local_variable_types
  Map<String, _Provider>? providers = _namedProviders[name];
  if (!(providers?.containsKey(typeName) ?? false)) {
    T? res;
    if (autoRegister) {
      res = searchForImplementation<T>(name);
    }
    return res == null ? null : Instance(res);
  }
  if (providers == null) {
    return null;
  }

  final indexOf = _loadingStack.indexOf(typeName);
  if (indexOf > -1 && indexOf < _loadingStack.length - 1) {
    throw ('Circular dependency detected between the following: $_loadingStack - when loading $typeName');
  }

  _loadingStack.add(typeName);
  final instance = providers[typeName]?.get(this);
  _loadingStack.removeLast();
  return instance;
}