Skip to content

Commit

Permalink
Extend singleton and provided instance docs
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan committed Aug 3, 2024
1 parent c156143 commit 4c97347
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
45 changes: 44 additions & 1 deletion docs/providers/provided_instance.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,46 @@
# Provided instance

soon...
You can pass provider field values to other providers,
which will provide dependency injection.
To access the values of an object's fields inside a provider,
you need to use the `provided` property of the provider.

This is useful in cases when your entities depend on external data
from configuration files or environment variables.
You need to parse this external data and save it into a class or dataclass,
and the container will inject this data.

### Example
```python3
from dataclasses import dataclass

from injection import DeclarativeContainer, providers


@dataclass
class Settings:
env_1: str
env_2: int


class SomeService:
def __init__(self, env_1: str, env_2: int):
self.env_1 = env_1
self.env_2 = env_2


class Container(DeclarativeContainer):
settings = providers.Singleton(Settings, env_1="value", env_2=193)

service = providers.Transient(
SomeService,
env_1=settings.provided.env_1,
env_2=settings.provided.env_2,
)


if __name__ == "__main__":
resolved_service = Container.service()
assert resolved_service.env_1 == "value"
assert resolved_service.env_2 == 193
```
28 changes: 27 additions & 1 deletion docs/providers/singleton.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
**Singleton** provider creates and returns a new object on the first call
and caches it, and on subsequent calls it returns the cached object.

## Example
### Example

```python3
from dataclasses import dataclass
Expand All @@ -28,3 +28,29 @@ if __name__ == "__main__":
assert instance1.field == 15

```

## Resetting memoized object

To **reset a memorized object** you need to call the `reset` method of the Singleton provider.

### Example

```python3
from injection import DeclarativeContainer, providers


class SomeClass: ...


if __name__ == "__main__":
provider = providers.Singleton(SomeClass)
obj = provider()
obj2 = provider()

assert obj is obj2
provider.reset()

obj3 = provider()
assert obj is not obj3
assert obj2 is not obj3
```

0 comments on commit 4c97347

Please sign in to comment.