Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about FastAPI's dependency injection and its reusability

from fastapi import Depends, FastAPI

class MyDependency:
    def __init__(self):
        # Perform initialization logic here
        pass

    def some_method(self):
        # Perform some operation
        pass

def get_dependency():
    # Create and return an instance of the dependency
    return MyDependency()

app = FastAPI()

@app.get("/example")
def example(dependency: MyDependency = Depends(get_dependency)):
    dependency.some_method()

For the code snippet above, does subsequent visits to /example create a new instance of the MyDependency object each time? If so, how can I avoid that?

like image 685
Michael Xia Avatar asked Oct 25 '25 06:10

Michael Xia


1 Answers

Yes, each request will receive a new instance.

If you don't want that to happen, use a cache decorator, such as the built-in lru_cache in functools: - it's just a regular function, so any decorators will still be invoked (since they replace the original function with a new one which wraps the old one):

from functools import lru_cache

...

@lru_cache
def get_dependency():
    # Create and return an instance of the dependency
    return MyDependency()

However, if you use the same dependency multiple places in the hiearchy (for the same request), the same value will be re-used.

If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.

like image 180
MatsLindh Avatar answered Oct 26 '25 19:10

MatsLindh