New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Inject dependency into a class attr #411
Comments
Hello @brunopereira27 , You can do it with cache_provider = providers.Singleton(Cache)
user_factory = providers.Factory(User)
user.add_attributes(cache=cache_provider)
user = user_factory()
assert isinstance(user.cache, Cache) You didn't find it because I didn't document that. I'm sorry about that. I already have a backlog item to update documentation. |
The same works with |
Thanks for your quick answer! As a consequence, I cannot provide a class attribute is that class is not created through a factory or as a singleton? Isn't there a way to provide a factory to the init function of a class? |
Few things:
Yes. You can use cache = providers.Singleton(Cache)
user_factory = providers.Factory(
User,
cache=cache.provider, # This will inject cache provider instead of Cache instance
)
user = user_factory()
asseert user.cache_provider is cache_provider
assert isinstance(user.cache(), Cache)
class User(object):
def __init__(self, cache=Provider[Container.cache]):
... You also need to have a container and call Current wiring can't make attribute injections, but I could upgrade it. Here is a prototype how it would look like: class User(object):
cache = Provider[Container.cache] Also you could use string identifiers to do not pull a container: class User(object):
cache = Provider['cache'] I started working on it. Will probably take a few more days. How does it look to you? |
Done in version |
Closing this issue. Feel free to comment if anything. |
Hello,
Sorry if this question already has been answered somewhere but I went through the doc extensively and couldn't find anything.
I would like to inject a dependency for a class attribute, but couldn't find any way of doing it.
Something similar from python-inject:
Thanks for your help
The text was updated successfully, but these errors were encountered: