Add some examples from presentation

This commit is contained in:
Roman Mogilatov 2016-06-02 20:25:45 +03:00
parent bf9b1205b6
commit 6701445e9f
5 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,21 @@
"""IoC container example."""
import collections
import dependency_injector.containers as containers
import dependency_injector.providers as providers
class Container(containers.DeclarativeContainer):
"""IoC container."""
engine_factory = providers.Factory(collections.namedtuple('Engine', []))
car_factory = providers.Factory(collections.namedtuple('Car', ['engine']),
engine=engine_factory)
if __name__ == '__main__':
car1 = Container.car_factory()
car2 = Container.car_factory()
assert car1 is not car2
assert car1.engine is not car2.engine

View File

@ -0,0 +1,13 @@
"""Factory provider example."""
from dependency_injector import providers
object_factory = providers.Factory(object)
if __name__ == '__main__':
object1 = object_factory()
object2 = object_factory()
assert object1 is not object2
assert isinstance(object1, object) and isinstance(object2, object)

View File

@ -0,0 +1,17 @@
"""Factory provider keyword argument injections example."""
import collections
import dependency_injector.providers as providers
engine_factory = providers.Factory(collections.namedtuple('Engine', []))
car_factory = providers.Factory(collections.namedtuple('Car', ['engine']),
engine=engine_factory)
if __name__ == '__main__':
car1 = car_factory()
car2 = car_factory()
assert car1 is not car2
assert car1.engine is not car2.engine

View File

@ -0,0 +1,15 @@
"""Overriding of factory provider example."""
from dependency_injector import providers
object_factory = providers.Factory(object)
object_factory.override(providers.Factory(list))
if __name__ == '__main__':
object1 = object_factory()
object2 = object_factory()
assert object1 is not object2
assert isinstance(object1, list) and isinstance(object2, list)

16
examples/speech/inject.py Normal file
View File

@ -0,0 +1,16 @@
"""@inject decorator example."""
from container import Container
from dependency_injector.injections import inject
@inject(car1=Container.car_factory)
@inject(car2=Container.car_factory)
def main(car1, car2):
"""Main function."""
assert car1 is not car2
assert car1.engine is not car2.engine
if __name__ == '__main__':
main()