resolve<T> method
Resolves a type from the container.
Creates or retrieves an instance of the specified type. Handles singleton caching, contextual resolution, and circular dependency detection.
T - The type to resolve
context - Optional context for contextual bindings
Returns the resolved instance
Throws ServiceNotFoundException if the type is not registered
Throws CircularDependencyException if circular dependency detected
Implementation
@override
T resolve<T>([String? context]) {
if (_resolving.contains(T)) {
throw CircularDependencyException(
'Circular dependency detected while resolving $T',
);
}
if (_instances.containsKey(T)) {
return _instances[T] as T;
}
_Binding? binding;
if (context != null && _contextualBindings.containsKey(context)) {
binding = _contextualBindings[context]![T];
}
binding ??= _bindings[T];
if (binding == null) {
if (_missingBindingHandler != null) {
_missingBindingHandler!(T);
// Try to find binding again
binding = _bindings[T];
}
if (binding == null) {
throw ServiceNotFoundException('Service $T not registered');
}
}
_resolving.add(T);
try {
final instance = binding.getInstance(this);
if (binding.singleton && !binding.lazy) {
_instances[T] = instance;
}
return instance as T;
} finally {
_resolving.remove(T);
}
}