Edit section about specialized factory provider

This commit is contained in:
Roman Mogylatov 2020-08-31 16:41:38 -04:00
parent 46935b3152
commit 091dc128fd
2 changed files with 13 additions and 14 deletions

View File

@ -92,17 +92,17 @@ attribute of the provider that you're going to inject.
.. note:: Any provider has a ``.provider`` attribute.
Factory providers specialization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Specializing the provided type
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:py:class:`Factory` provider could be specialized for any kind of needs via
creating its subclasses.
One of such specialization features is a limitation to :py:class:`Factory`
provided type:
You can create a specialized ``Factory`` provider that provides only specific type. For doing
this you need to create a subclass of the ``Factory`` provider and define the ``provided_type``
class attribute.
.. literalinclude:: ../../examples/providers/factory_provided_type.py
:language: python
:lines: 3-
:emphasize-lines: 12-14
.. _abstract_factory_providers:

View File

@ -1,30 +1,29 @@
"""`Factory` specialization with limitation to provided type example."""
import dependency_injector.providers as providers
import dependency_injector.errors as errors
from dependency_injector import providers, errors
class BaseService:
"""Base service class."""
...
class SomeService(BaseService):
"""Some service."""
...
class ServiceProvider(providers.Factory):
"""Service provider."""
provided_type = BaseService
# Creating service provider with correct provided type:
# Creating service provider with a correct provided type:
some_service_provider = ServiceProvider(SomeService)
# Trying to create service provider incorrect provided type:
# Trying to create service provider an incorrect provided type:
try:
some_service_provider = ServiceProvider(object)
except errors.Error as exception:
print(exception)
# The output is:
# <class '__main__.ServiceProvider'> can provide only
# <class '__main__.BaseService'> instances