2015-11-13 16:58:29 +00:00
|
|
|
Writing of custom providers
|
2015-11-29 09:53:45 +00:00
|
|
|
---------------------------
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2015-11-29 21:30:48 +00:00
|
|
|
.. currentmodule:: dependency_injector.providers
|
2015-11-23 16:45:04 +00:00
|
|
|
|
2015-08-31 13:31:38 +00:00
|
|
|
List of *Dependency Injector* providers could be widened with custom providers.
|
2015-07-27 22:29:31 +00:00
|
|
|
|
|
|
|
Below are some tips and recommendations that have to be met:
|
|
|
|
|
2015-09-02 14:20:19 +00:00
|
|
|
1. Every custom provider has to extend base provider class -
|
2015-11-23 16:45:04 +00:00
|
|
|
:py:class:`Provider`.
|
|
|
|
2. Cusom provider's ``__init__()`` could be overriden, but parent's
|
|
|
|
initializer (:py:meth:`Provider.__init__`) has to be called.
|
2015-07-27 22:29:31 +00:00
|
|
|
3. Providing strategy has to be implemented in custom provider's
|
2015-11-23 16:45:04 +00:00
|
|
|
:py:meth:`Provider._provide` method. All ``*args`` & ``**kwargs``
|
|
|
|
that will be recieved by :py:meth:`Provider.__call__` will be
|
|
|
|
transefed to custom provider's :py:meth:`Provider._provide`.
|
2015-07-27 22:29:31 +00:00
|
|
|
4. If custom provider is based on some standard providers, it is better to
|
|
|
|
use delegation of standard providers, then extending of them.
|
|
|
|
5. If custom provider defines any attributes, it is good to list them in
|
2015-08-31 13:31:38 +00:00
|
|
|
``__slots__`` attribute (as *Dependency Injector* does). It can save
|
|
|
|
some memory.
|
2015-11-23 16:45:04 +00:00
|
|
|
6. If custom provider deals with injections, it is strongly recommended
|
|
|
|
to be consistent with :py:class:`Factory`, :py:class:`Singleton` and
|
|
|
|
:py:class:`Callable` providers style.
|
2015-07-27 22:29:31 +00:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
.. image:: /images/providers/custom_provider.png
|
|
|
|
:width: 100%
|
|
|
|
:align: center
|
|
|
|
|
2015-08-03 12:47:42 +00:00
|
|
|
.. literalinclude:: ../../examples/providers/custom_factory.py
|
|
|
|
:language: python
|
2016-04-11 07:43:02 +00:00
|
|
|
:linenos:
|