find<S> method
Retrieves the registered instance of type S.
If the dependency is not found in the current scope, it recursively searches parent scopes.
Parameters:
tag: Optional unique identifier used during registration.
Throws an Exception if no registration is found for S and tag.
Implementation
S find<S>({String? tag}) {
// ULTRA-FAST PATH: Direct instance cache lookup (no indirection)
if (tag == null) {
final cached = _instanceCache[S];
if (cached != null) {
return cached as S;
}
// Fast path: Type registry lookup
final info = _typeRegistry[S];
if (info != null) {
// Already instantiated singleton - cache and return
final instance = info.instance;
if (instance != null && !info.isFactory) {
_instanceCache[S] = instance;
return instance as S;
}
// Slower path: needs instantiation
final result =
_findLocal<S>(info as LevitDependency<S>, S.toString(), null);
// Cache if it's a singleton (not factory)
if (!info.isFactory && info.instance != null) {
_instanceCache[S] = info.instance;
}
return result;
}
// Try cached parent scope (Type-based)
final cachedScope = _typeResolutionCache[S];
if (cachedScope != null) {
return cachedScope.find<S>();
}
// Try parent
if (_parentScope != null) {
try {
final instance = _parentScope!.find<S>();
_typeResolutionCache[S] = _parentScope!;
return instance;
} catch (_) {
// Fallthrough to throw below
}
}
throw Exception(
'LevitScope($name): Type "$S" is not registered.\n'
'Not found in scope or any parent.',
);
}
// SLOW PATH: With tag - use String-based registry
final key = _getKey<S>(tag);
final info = _registry[key];
if (info != null) {
return _findLocal<S>(info as LevitDependency<S>, key, tag);
}
// Try Cache
final cachedScope = _resolutionCache[key];
if (cachedScope != null) {
return cachedScope.find<S>(tag: tag);
}
// Try Parent
if (_parentScope != null) {
try {
final instance = _parentScope!.find<S>(tag: tag);
_cacheScope(key, _parentScope!);
return instance;
} catch (_) {
// Fallthrough to throw below
}
}
throw Exception(
'LevitScope($name): Type "$S" with tag "$tag" is not registered.\n'
'Not found in scope or any parent.',
);
}