ServiceContainer class

A powerful dependency injection container with advanced features.

The ServiceContainer provides a robust dependency injection system supporting interfaces, contextual bindings, singletons, lazy loading, and circular dependency detection. It implements the ContainerInterface and serves as the core of the framework's service management.

Key features:

  • Type-safe dependency resolution using generics
  • Singleton and transient binding modes
  • Lazy singleton instantiation
  • Contextual bindings for different resolution contexts
  • Circular dependency detection and prevention
  • Instance registration for pre-created objects

Example usage:

final container = ServiceContainer();

// Register a transient service
container.bind<Logger>((c) => ConsoleLogger());

// Register a singleton
container.singleton<Database>((c) => Database.connect());

// Register with dependencies
container.bind<UserService>((c) => UserService(
  c.resolve<Logger>(),
  c.resolve<Database>(),
));

// Resolve services
final userService = container.resolve<UserService>();
Implemented types

Constructors

ServiceContainer()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

bind<T>(dynamic factory(ContainerInterface), {bool singleton = false}) → void
Binds an implementation to an abstract type.
override
bindWhen<T>(String context, dynamic factory(ContainerInterface), {bool singleton = false}) → void
Binds an implementation to an interface when requested within a specific context.
override
flush() → void
Clears all bindings and instances.
override
has<T>([String? context]) bool
Checks if a service is registered.
override
instance<T>(T instance) → void
Registers an already created instance as a singleton.
override
lazySingleton<T>(dynamic factory(ContainerInterface)) → void
Registers a lazy singleton instance.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
resolve<T>([String? context]) → T
Resolves a type from the container.
override
resolveAll<T>() List<T>
Resolves all registered implementations of a given type.
override
resolveType(Type type, [String? context]) → dynamic
Resolves and returns an instance of the given type.
override
setMissingBindingHandler(void handler(Type type)) → void
Sets a handler to be called when a service is not found.
override
singleton<T>(dynamic factory(ContainerInterface)) → void
Registers a singleton instance.
override
toString() String
A string representation of this object.
inherited
unbind<T>([String? context]) → void
Removes a service registration.
override

Operators

operator ==(Object other) bool
The equality operator.
inherited