2020-09-03 00:59:55 +00:00
|
|
|
"""Custom provider example."""
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2020-09-03 21:56:54 +00:00
|
|
|
from dependency_injector import containers, providers
|
2015-07-27 22:29:31 +00:00
|
|
|
|
|
|
|
|
2020-09-03 00:59:55 +00:00
|
|
|
class CustomFactory(providers.Provider):
|
2015-07-27 22:29:31 +00:00
|
|
|
|
|
|
|
__slots__ = ('_factory',)
|
|
|
|
|
2020-09-03 00:59:55 +00:00
|
|
|
def __init__(self, provides, *args, **kwargs):
|
|
|
|
self._factory = providers.Factory(provides, *args, **kwargs)
|
2020-01-26 23:41:36 +00:00
|
|
|
super().__init__()
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2020-09-03 00:59:55 +00:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
copied = memo.get(id(self))
|
|
|
|
if copied is not None:
|
|
|
|
return copied
|
|
|
|
|
|
|
|
copied = self.__class__(
|
|
|
|
self._factory.provides,
|
|
|
|
*providers.deepcopy(self._factory.args, memo),
|
|
|
|
**providers.deepcopy(self._factory.kwargs, memo),
|
|
|
|
)
|
|
|
|
self._copy_overridings(copied, memo)
|
2015-11-23 16:45:04 +00:00
|
|
|
|
2020-09-03 00:59:55 +00:00
|
|
|
return copied
|
|
|
|
|
|
|
|
def _provide(self, args, kwargs):
|
2015-07-27 22:29:31 +00:00
|
|
|
return self._factory(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2020-09-03 21:56:54 +00:00
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
factory = CustomFactory(object)
|
2020-09-03 00:59:55 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-09-03 21:56:54 +00:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
object1 = container.factory()
|
2020-09-03 00:59:55 +00:00
|
|
|
assert isinstance(object1, object)
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2020-09-03 21:56:54 +00:00
|
|
|
object2 = container.factory()
|
2020-09-03 00:59:55 +00:00
|
|
|
assert isinstance(object1, object)
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2020-09-03 00:59:55 +00:00
|
|
|
assert object1 is not object2
|