Dependency providers

Dependency provider can be useful for development of self-sufficient libraries / modules / applications that have required external dependencies.

For example, you have created self-sufficient library / module / application, that has dependency on database connection.

Second step you want to do is to make this software component to be easy reusable by wide amount of developers and to be easily integrated into many applications.

It may be good idea, to move all external dependencies (like database connection) to the top level and make them to be injected on your software component’s initialization. It will make third party developers feel themselves free about integration of your component in their applications, because they would be able to find right place / right way for doing this in their application’s architectures.

At the same time, you can be sure, that your external dependency will be satisfied with appropriate instance.



Class UsersService is a part of some library. UsersService has dependency on database connection, which can be satisfied with any DBAPI 2.0 database connection. Being a self-sufficient library, UsersService doesn’t hardcode any kind of database management logic. Instead of this, UsersService has external dependency, that has to be satisfied by client’s code, out of library’s scope.

"""`Dependency` providers example."""

import sqlite3
import contextlib

import dependency_injector.providers as providers

class UsersService:
    """Example class UsersService.

    UsersService has dependency on DBAPI 2.0 database connection.

    def __init__(self, database):
        """Initialize instance.

        :param database: Database connection.
        :type database: sqlite3.dbapi2.Connection
        self.database = database
        self.database.row_factory = sqlite3.dbapi2.Row

    def init_database(self):
        """Initialize database, if it has not been initialized yet."""
        with contextlib.closing(self.database.cursor()) as cursor:
              CREATE TABLE IF NOT EXISTS users(
                name VARCHAR(32)

    def create(self, name):
        """Create user with provided name and return his id."""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
            return cursor.lastrowid

    def get_by_id(self, id):
        """Return user info by user id."""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('SELECT id, name FROM users WHERE id=?', (id,))
            return cursor.fetchone()

# Database and UsersService providers:
database = providers.Dependency(instance_of=sqlite3.dbapi2.Connection)
users_service_factory = providers.Factory(UsersService,

# Out of library's scope.
# Setting database provider:

# Creating UsersService instance:
users_service = users_service_factory()

# Initializing UsersService database:

# Creating test user and retrieving full information about him:
test_user_id = users_service.create(name='test_user')
test_user = users_service.get_by_id(test_user_id)

# Making some asserts:
assert test_user['id'] == 1
assert test_user['name'] == 'test_user'