-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.py
More file actions
65 lines (41 loc) · 1.64 KB
/
main.py
File metadata and controls
65 lines (41 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from blacksheep import Application, get
from blacksheep.server.controllers import Controller
from dependency_injector import containers, providers
from app.di import DependencyInjectorConnector
class APIClient: ...
class SomeService:
def __init__(self, api_client: APIClient) -> None:
self.api_client = api_client
class AnotherService: ...
# Define the Dependency Injector container
class AppContainer(containers.DeclarativeContainer):
APIClient = providers.Singleton(APIClient)
SomeService = providers.Factory(SomeService, api_client=APIClient)
AnotherService = providers.Factory(AnotherService)
# Create the container instance
container = AppContainer()
app = Application(
services=DependencyInjectorConnector(container), show_error_details=True
)
@get("/")
def home(service: SomeService):
# DependencyInjector resolved the dependencies
assert isinstance(service, SomeService)
assert isinstance(service.api_client, APIClient)
return id(service)
class TestController(Controller):
def __init__(self, another_dep: AnotherService) -> None:
super().__init__()
self._another_dep = (
another_dep # another_dep is resolved by Dependency Injector
)
@app.controllers_router.get("/controller-test")
def controller_test(self, service: SomeService):
# DependencyInjector resolved the dependencies
assert isinstance(self._another_dep, AnotherService)
assert isinstance(service, SomeService)
assert isinstance(service.api_client, APIClient)
return id(service)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, port=44777)