0
# Scoped Services
1
2
Scoped service management through ActivationScope context managers. Enables per-request or per-operation service scoping with automatic cleanup and support for nested scopes.
3
4
## Capabilities
5
6
### Activation Scope Initialization
7
8
Creates a new activation scope for managing scoped service lifetimes within a specific context.
9
10
```python { .api }
11
def __init__(self, provider: Optional[Services] = None, scoped_services: Optional[Dict[Union[Type[T], str], T]] = None):
12
"""
13
Initialize an ActivationScope.
14
15
Args:
16
provider: Services provider for service resolution
17
scoped_services: Optional dictionary of pre-scoped service instances
18
"""
19
```
20
21
### Scoped Service Resolution
22
23
Resolves services within the current scope, creating scoped instances as needed and reusing them within the scope lifetime.
24
25
```python { .api }
26
def get(self, desired_type: Union[Type[T], str], scope: Optional[ActivationScope] = None, *, default: Optional[Any] = ...) -> T:
27
"""
28
Get a service instance within this scope.
29
30
Args:
31
desired_type: Type or name of service to resolve
32
scope: Optional nested scope (defaults to current scope)
33
default: Default value if service cannot be resolved
34
35
Returns:
36
Service instance (scoped or singleton as appropriate)
37
38
Raises:
39
CannotResolveTypeException: If service cannot be resolved and no default provided
40
"""
41
```
42
43
### Scope Cleanup
44
45
Manually dispose of the scope and clean up scoped service instances.
46
47
```python { .api }
48
def dispose(self):
49
"""
50
Dispose of the scope and clean up scoped services.
51
52
Calls dispose() on any scoped services that implement it.
53
"""
54
```
55
56
### Context Manager Support
57
58
ActivationScope implements context manager protocol for automatic resource cleanup.
59
60
```python { .api }
61
def __enter__(self):
62
"""
63
Enter the scope context.
64
65
Returns:
66
The ActivationScope instance
67
"""
68
69
def __exit__(self, exc_type, exc_val, exc_tb):
70
"""
71
Exit the scope context and automatically dispose resources.
72
73
Args:
74
exc_type: Exception type (if any)
75
exc_val: Exception value (if any)
76
exc_tb: Exception traceback (if any)
77
"""
78
```
79
80
Usage examples:
81
82
```python
83
# Manual scope management
84
scope = services.create_scope()
85
try:
86
scoped_service = scope.get(ScopedService)
87
# Use scoped service
88
finally:
89
scope.dispose()
90
91
# Automatic scope management with context manager
92
with services.create_scope() as scope:
93
scoped_service = scope.get(ScopedService)
94
database_service = scope.get(DatabaseService)
95
# Services automatically disposed when exiting context
96
```
97
98
### Tracking Activation Scope
99
100
Experimental class for advanced nested scope scenarios with tracking capabilities.
101
102
```python { .api }
103
class TrackingActivationScope(ActivationScope):
104
def __init__(self, provider=None, scoped_services=None):
105
"""
106
Initialize a TrackingActivationScope for nested scope support.
107
108
Args:
109
provider: Services provider for service resolution
110
scoped_services: Optional dictionary of pre-scoped services
111
"""
112
```
113
114
## Scoped Service Patterns
115
116
### Web Request Scoping
117
118
Common pattern for web applications where services are scoped per HTTP request:
119
120
```python
121
# In web framework integration
122
def handle_request(request):
123
with services.create_scope() as scope:
124
# Register request-specific services
125
request_context = RequestContext(request)
126
scope.set(RequestContext, request_context)
127
128
# Resolve and execute handler
129
handler = scope.get(RequestHandler)
130
return handler.process(request)
131
```
132
133
### Transaction Scoping
134
135
Pattern for database transactions where services are scoped per transaction:
136
137
```python
138
def process_business_operation():
139
with services.create_scope() as scope:
140
# Scoped database connection
141
db_service = scope.get(DatabaseService)
142
143
try:
144
# Business logic using scoped services
145
user_service = scope.get(UserService)
146
result = user_service.create_user(user_data)
147
db_service.commit()
148
return result
149
except Exception:
150
db_service.rollback()
151
raise
152
```
153
154
### Nested Scopes
155
156
Advanced pattern using nested scopes for complex service hierarchies:
157
158
```python
159
# Parent scope
160
with services.create_scope() as parent_scope:
161
parent_service = parent_scope.get(ParentService)
162
163
# Child scope inheriting from parent
164
with parent_scope.create_scope() as child_scope:
165
child_service = child_scope.get(ChildService)
166
# Child scope can access parent scoped services
167
same_parent = child_scope.get(ParentService) # Same instance as parent_service
168
```