Specialization of the container provider typeΒΆ

You can make a restriction of the DeclarativeContainer provider type:

import abc

from dependency_injector import containers, providers


class Service(metaclass=abc.ABCMeta):
    ...


class UserService(Service):
    ...


class ServiceProvider(providers.Factory):

    provided_type = Service


class ServiceContainer(containers.DeclarativeContainer):

    provider_type = ServiceProvider


class MyServices(ServiceContainer):

    user_service = ServiceProvider(UserService)


class ImproperServices(ServiceContainer):

    other_provider = providers.Factory(object)

The emphasized lines will cause an error because other_provider is not a subtype of the ServiceProvider. This helps to control the content of the container.

The same works for the DynamicContainer:

import abc

from dependency_injector import containers, providers


class Service(metaclass=abc.ABCMeta):
    ...


class UserService(Service):
    ...


class ServiceProvider(providers.Factory):

    provided_type = Service


services = containers.DynamicContainer()
services.provider_type = ServiceProvider

services.user_service = ServiceProvider(UserService)
services.other_provider = providers.Factory(object)

The emphasized line will also cause an error.