Repository navigation
Difference between Delegate and non-Delegate #739
Replies: 1 comment
|
Here, “as-is” means inject the provider object itself, so the receiving object can call it later. Normally, a provider used as a dependency is called while constructing its consumer, and the consumer receives its result: from dependency_injector import providers
class User:
pass
class Service:
def __init__(self, user):
self.user = user
user_factory = providers.Factory(User)
with_instance = providers.Factory(Service, user=user_factory)
with_factory = providers.Factory(Service, user=user_factory.provider)
service1 = with_instance() # service1.user is a User instance
service2 = with_factory() # service2.user is user_factory itself
user = service2.user() # create a User when the consumer needs one
There is also a related distinction for delegated = providers.DelegatedFactory(User)
consumer = providers.Factory(Service, user=delegated)
service = consumer() # service.user is delegated
user = service.user() # creates a UserUse the ordinary factory when the consumer should receive an already-created dependency. Pass its delegate when the consumer needs to decide when or how often to create one. See passing providers to objects, Delegate, and DelegatedFactory. |
Uh oh!
There was an error while loading. Please reload this page.
What is the difference between a delegate and a non-delegate? All the documentation says is the object is return "as-is" which doesn't mean much to me?
All reactions