python-dependency-injector/examples/providers/dependency.py
Roman Mogylatov 839a319831
Better error message for dependency provider (#395)
* Add prototype for flat resolving

* Add working prototype for sample 1 and 3

* Add working prototype, requires deep refactoring

* Update DependenciesContainer to handle Contrainer provider

* Fix Dependency provider copying issue

* Add hardening fix for Self provider to avoid copying bugs

* Fix flaky container copy issue

* Rename set_parent() to assign_parent()

* Refactor Dependency provider and its typing stub

* Add tests for Dependency provider

* Update makefile to run coverage when tests fail

* Clean up DependenciesContainer provider and add tests

* Clean up Container provider and add tests

* Clean up container instance and add tests

* Refactor isinstance() checks

* Clean up DeclarativeContainer and add tests

* Update docs and examples

* Update changelog

* Revoke makefile change
2021-02-13 09:16:38 -05:00

46 lines
1.0 KiB
Python

"""`Dependency` provider example."""
import abc
import dataclasses
from dependency_injector import containers, providers
class DbAdapter(metaclass=abc.ABCMeta):
...
class SqliteDbAdapter(DbAdapter):
...
class PostgresDbAdapter(DbAdapter):
...
@dataclasses.dataclass
class UserService:
database: DbAdapter
class Container(containers.DeclarativeContainer):
database = providers.Dependency(instance_of=DbAdapter)
user_service = providers.Factory(
UserService,
database=database,
)
if __name__ == '__main__':
container1 = Container(database=providers.Singleton(SqliteDbAdapter))
container2 = Container(database=providers.Singleton(PostgresDbAdapter))
assert isinstance(container1.user_service().database, SqliteDbAdapter)
assert isinstance(container2.user_service().database, PostgresDbAdapter)
container3 = Container(database=providers.Singleton(object))
container3.user_service() # <-- raises error:
# <object ...> is not an instance of DbAdapter