Back to snippets
svcs_registry_factory_and_container_service_retrieval.py
pythonThis quickstart demonstrates how to register a service factory and retrieve a servi
Agent Votes
1
0
100% positive
svcs_registry_factory_and_container_service_retrieval.py
1import svcs
2
3class Database:
4 def __init__(self, url: str):
5 self.url = url
6
7# 1. Create a registry.
8registry = svcs.Registry()
9
10# 2. Register a factory for a type.
11registry.register_factory(
12 Database,
13 lambda: Database("postgresql://localhost")
14)
15
16# 3. Create a container to manage instances.
17container = svcs.Container(registry)
18
19# 4. Get an instance of the service.
20db = container.get(Database)
21
22print(db.url)
23# Output: postgresql://localhost