Scoping of dependables
In FastAPI, the scope of dependables can be either a new instance or a singleton. FastAPI’s DI does not support the creation of singleton objects by default. In every execution of an API service with dependencies, FastAPI always fetches a new instance of each wired dependable, which can be proven by getting the object ID using id()
.
A singleton
object is created only once by a container, no matter how many times the framework injects it. Its object ID remains the same the entire runtime of the application. Services and repository classes are preferred to be singleton to control the increase of memory utilization of the application. And since it is not easy to create a singleton with FastAPI, we can use either Dependency Injector or Lagom.
There is a Singleton
provider in Dependency Injector that is responsible for the creation of singleton dependencies. This provider was mentioned already during the discussions on its DeclarativeContainer
setup....