Improve providers documentation
This commit is contained in:
parent
bdca92269e
commit
f90eb5fb21
|
@ -10,7 +10,13 @@ For those new to dependency-injection and/or Guice, though, some of the terminol
|
|||
Provider
|
||||
````````
|
||||
|
||||
A means of providing an instance of a type. Built-in providers include `ClassProvider` (creates a new instance from a class), `InstanceProvider` (returns an existing instance directly), `CallableProvider` (provides an instance by calling a function).
|
||||
A means of providing an instance of a type. Built-in providers include:
|
||||
|
||||
* :class:`~injector.ClassProvider` - creates a new instance from a class
|
||||
* :class:`~injector.InstanceProvider` - returns an existing instance directly
|
||||
* :class:`~injector.CallableProvider` - provides an instance by calling a function
|
||||
|
||||
In order to create custom provider you need to subclass :class:`~injector.Provider` and override its :meth:`~injector.Provider.get` method.
|
||||
|
||||
Scope
|
||||
`````
|
||||
|
|
37
injector.py
37
injector.py
|
@ -141,7 +141,26 @@ class ClassProvider(Provider):
|
|||
|
||||
|
||||
class CallableProvider(Provider):
|
||||
"""Provides something using a callable."""
|
||||
"""Provides something using a callable.
|
||||
|
||||
The callable is called every time new value is requested from the provider.
|
||||
|
||||
::
|
||||
|
||||
>>> key = Key('key')
|
||||
>>> def factory():
|
||||
... print('providing')
|
||||
... return []
|
||||
...
|
||||
>>> def configure(binder):
|
||||
... binder.bind(key, to=CallableProvider(factory))
|
||||
...
|
||||
>>> injector = Injector(configure)
|
||||
>>> injector.get(key) is injector.get(key)
|
||||
providing
|
||||
providing
|
||||
False
|
||||
"""
|
||||
|
||||
def __init__(self, callable):
|
||||
self._callable = callable
|
||||
|
@ -151,7 +170,21 @@ class CallableProvider(Provider):
|
|||
|
||||
|
||||
class InstanceProvider(Provider):
|
||||
"""Provide a specific instance."""
|
||||
"""Provide a specific instance.
|
||||
|
||||
::
|
||||
|
||||
>>> my_list = Key('my_list')
|
||||
>>> def configure(binder):
|
||||
... binder.bind(my_list, to=InstanceProvider([]))
|
||||
...
|
||||
>>> injector = Injector(configure)
|
||||
>>> injector.get(my_list) is injector.get(my_list)
|
||||
True
|
||||
>>> injector.get(my_list).append('x')
|
||||
>>> injector.get(my_list)
|
||||
['x']
|
||||
"""
|
||||
|
||||
def __init__(self, instance):
|
||||
self._instance = instance
|
||||
|
|
Loading…
Reference in New Issue