createScope static method
Create a scoped container that inherits from the global Spot registry.
The scoped container:
- Can register its own dependencies that shadow global ones
- Falls back to global Spot registry for dependencies not registered locally
- Can be disposed independently without affecting global registry
- Supports nested scopes via SpotContainer.createChild
This is useful for:
- Test isolation (override dependencies without affecting production code)
- Feature-specific dependency trees
- Request-scoped dependencies (e.g., web request handlers)
- Temporary state that needs cleanup
Returns: A new SpotContainer that uses Spot's global registry as parent
Example:
// Global dependencies
Spot.registerSingle<IApiClient, ApiClient>((get) => ApiClient());
// Create test scope
final testScope = Spot.createScope();
testScope.registerSingle<IApiClient, MockApiClient>(
(get) => MockApiClient(),
);
// Test code uses test scope
final mockClient = testScope.spot<IApiClient>(); // Gets MockApiClient
// Production code uses global scope
final realClient = spot<IApiClient>(); // Gets ApiClient
// Cleanup test scope (doesn't affect global)
testScope.dispose();
// Nested scopes
final childScope = testScope.createChild();
childScope.registerSingle<ILogger, TestLogger>((get) => TestLogger());
// childScope inherits from testScope, which inherits from global
See also:
- SpotContainer for scoped container implementation
- SpotContainer.createChild for creating nested scopes
Implementation
static SpotContainer createScope() {
// Create a container that uses Spot's static registry/cache as parent
// This is a bit of a hack since Spot is static, but we can create a wrapper
return _GlobalSpotContainer();
}