from injector import Module, singleton class MyModule(Module): def configure(self, binder): # Always provide the same instance (Singleton) binder.bind(Database, to=Database(), scope=singleton) Use code with caution. Copied to clipboard
Instantiate the Injector and use it to retrieve your root object.
: Defines "bindings"—the rules for how an interface (like an abstract class) maps to a specific implementation. injector.py
from injector import Injector injector = Injector([MyModule()]) # Pass your modules here service = injector.get(Service) # Automatically creates Database and Service print(service.db.status) # "Connected" Use code with caution. Copied to clipboard
For further details, consult the official Injector documentation . Make Your Django Project Less Confusing with Design Pattern Common scopes include singleton (one instance for the
: Control object lifetimes. Common scopes include singleton (one instance for the whole app) and NoScope (new instance every time).
: The library is commonly used to simplify SOLID principles in frameworks like Django and FastAPI . Copied to clipboard
from injector import inject class Database: def __init__(self): self.status = "Connected" class Service: @inject def __init__(self, db: Database): self.db = db Use code with caution. Copied to clipboard
Archiver|手机版|海欣资源 ( 湘ICP备2021008090号-1 )|网站地图
GMT+8, 2026-3-9 06:32 , Gzip On, MemCached On.