ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.99k stars 305 forks source link

Override a dependency in a container subclass #778

Open warvariuc opened 10 months ago

warvariuc commented 10 months ago
import dependency_injector.containers as dic
import dependency_injector.providers as dip

class UnitOfWork:
    ...

class TestUnitOfWork(UnitOfWork):
    ...

class ApplicationContainer(dic.DeclarativeContainer):
    unit_of_work_class = dip.Callable(UnitOfWork)
    uow = dip.Factory(unit_of_work_class)

class TestApplicationContainer(ApplicationContainer):
    unit_of_work_class = dip.Callable(TestUnitOfWork)

container = TestApplicationContainer()
print(container.uow())
with container.unit_of_work_class.override(TestUnitOfWork):
    print(container.uow())

The output:

<__main__.UnitOfWork object at 0x110ae9ed0>
<__main__.UnitOfWork object at 0x110ae9ed0>

I would expect that container.uow() to return an instance of TestUnitOfWork, since container is an instance of TestApplicationContainer which has unit_of_work_class = dip.Callable(TestUnitOfWork).

container.unit_of_work_class.override(TestUnitOfWork) also doesn't work, as you can see...