Use cases mini application example

“Use cases” miniapp demonstrate usage of DependenciesContainer provider.

Example application

“Use cases” mini application has next structure:

use_cases/
    example/               <-- Example package
        __init__.py
        adapters.py
        use_cases.py
    containers.py          <-- Dependency injection containers
    run.py                 <-- Entrypoint

IoC containers

Listing of use_cases/containers.py:

 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
"""Dependency injection containers for 'Use Cases' example application."""

from dependency_injector import containers, providers

from example.adapters import SmtpEmailSender, EchoEmailSender
from example.use_cases import SignupUseCase


class Adapters(containers.DeclarativeContainer):
    """Adapters container."""

    email_sender = providers.Singleton(SmtpEmailSender)


class TestAdapters(containers.DeclarativeContainer):
    """Adapters container.

    This container is used for testing purposes.
    """

    email_sender = providers.Singleton(EchoEmailSender)


class UseCases(containers.DeclarativeContainer):
    """Use cases container."""

    adapters = providers.DependenciesContainer()

    signup = providers.Factory(SignupUseCase,
                               email_sender=adapters.email_sender)

Run application

Listing of run.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
"""Run 'Use Cases' example application."""

import sys

from containers import Adapters, TestAdapters, UseCases


if __name__ == '__main__':
    environment, email = sys.argv[1:]

    if environment == 'prod':
        adapters = Adapters()
    elif environment == 'test':
        adapters = TestAdapters()

    use_cases = UseCases(adapters=adapters)

    use_case = use_cases.signup()
    use_case.execute(email)

Instructions for running:

python run.py prod example@example.com  # Running in "production" environment
python run.py test example@example.com  # Running in "testing" environment