Skip to content

Commit

Permalink
update docs on context providers
Browse files Browse the repository at this point in the history
  • Loading branch information
lesnik512 committed Dec 29, 2024
1 parent 19d057a commit 976a0fc
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions docs/providers/context-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ class StorageServiceLocal(StorageService):
class StorageServiceRemote(StorageService):
...

def context_adapter_function(*, storage_backend: str | None = None, **_: object) -> str:
def selector_function(*, storage_backend: str | None = None, **_: object) -> str:
return storage_backend or "local"

class Dependencies(BaseGraph):
storage_service: providers.Selector[StorageService] = providers.Selector(
Scope.APP,
lambda: os.getenv("STORAGE_BACKEND", "local"),
selector_function,
local=providers.Factory(Scope.APP, StorageServiceLocal),
remote=providers.Factory(Scope.APP, StorageServiceRemote),
)
Expand All @@ -36,3 +36,22 @@ with Container(scope=Scope.APP, context={"storage_backend": "remote"}) as contai
print(type(Dependencies.storage_service.sync_resolve(container)))
# StorageServiceRemote
```

## ContextAdapter
- Receives context unpacked to callable object.
- Can be used in another providers to access data from context.

```python
from modern_di import BaseGraph, Container, Scope, providers


def context_adapter_function(*, storage_backend: str | None = None, **_: object) -> str:
return storage_backend or "local"

class Dependencies(BaseGraph):
context_adapter = providers.ContextAdapter(Scope.APP, context_adapter_function)

with Container(scope=Scope.APP, context={"storage_backend": "remote"}) as container:
print(Dependencies.context_adapter.sync_resolve(container))
# "remote"
```

0 comments on commit 976a0fc

Please sign in to comment.