Use global container for Dependency injection #99
jorgebenzeno
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
It should be interesting to use a container for dependency injection
Because if somone like me wants to extends the resolver using a different database we need to rewrite the whole code
even for test it's better for injecting memory database is needed or some mocks
What's do you think ?
app.py
from flask import Flask, jsonify
from flask_injector import FlaskInjector
from injector import inject, Binder
from services import DatabaseService, UserService
app = Flask(name)
Configure bindings
def configure(binder: Binder):
binder.bind(DatabaseService, to=DatabaseService, scope=singleton)
binder.bind(UserService, to=UserService, scope=singleton)
Inject dependencies into routes
@app.route('/user')
@Inject
def get_user(user_service: UserService):
return jsonify(user=user_service.get_user())
Setup FlaskInjector
FlaskInjector(app=app, modules=[configure])
if name == 'main':
app.run()
Beta Was this translation helpful? Give feedback.
All reactions