2020-09-03 03:59:55 +03:00
|
|
|
"""Custom provider example."""
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-04 00:56:54 +03:00
|
|
|
from dependency_injector import containers, providers
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
class CustomFactory(providers.Provider):
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
__slots__ = ('_factory',)
|
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
def __init__(self, provides, *args, **kwargs):
|
|
|
|
self._factory = providers.Factory(provides, *args, **kwargs)
|
2020-01-27 02:41:36 +03:00
|
|
|
super().__init__()
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03: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 19:45:04 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
return copied
|
|
|
|
|
|
|
|
def _provide(self, args, kwargs):
|
2015-07-28 01:29:31 +03:00
|
|
|
return self._factory(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2020-09-04 00:56:54 +03:00
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
factory = CustomFactory(object)
|
2020-09-03 03:59:55 +03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-09-04 00:56:54 +03:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
object1 = container.factory()
|
2020-09-03 03:59:55 +03:00
|
|
|
assert isinstance(object1, object)
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-04 00:56:54 +03:00
|
|
|
object2 = container.factory()
|
2020-09-03 03:59:55 +03:00
|
|
|
assert isinstance(object1, object)
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
assert object1 is not object2
|