mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-07-01 02:43:29 +03:00
Edit section about specialized factory provider
This commit is contained in:
parent
46935b3152
commit
091dc128fd
|
@ -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:
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue
Block a user