Dependency Injection (DI) म्हणजे एक ऑब्जेक्ट त्याच्या डिपेंडेन्सीज बाहेरून मिळवतो, त्याऐवजी स्वतः तयार न करता. हा Inversion of Control (IoC) चा एक प्रकार आहे: ऑब्जेक्ट्स जोडण्याची जबाबदारी उलट केली जाते - ऑब्जेक्ट पासून दूर गेली जाते आणि कॉलर किंवा कंटेनरला दिली जाते.
DI विना vs. DI सह
python
# WITHOUT DI — the class controls its own dependencies (tight coupling)
class OrderService:
def __init__(self):
self.repo = PostgresOrderRepo() # hard-wired; can't swap or test
# WITH DI — dependencies are passed in (loose coupling)
class OrderService:
def __init__(self, repo: OrderRepo): # any OrderRepo implementation
self.repo = repo
# wiring happens outside:
service = OrderService(PostgresOrderRepo()) # prod
test = OrderService(InMemoryOrderRepo()) # test — no DB needed
क्लास आता abstraction OrderRepo वर अवलंबून आहे, आणि इतर कोणी ठरवतो कोणता कंक्रिट सरबराज करायचा.
इंजेक्शनचे प्रकार
| प्रकार | कसे |
|---|---|
| Constructor | कंस्ट्रक्टरला पास केले जाते (पसंदीदा — आवश्यक deps स्पष्ट) |
| Setter | कंस्ट्रक्शननंतर मेथडद्वारे सेट केले जाते (ऐच्छिक deps) |
| Interface/container | एक framework रिझॉल्व करतो आणि इंजेक्ट करतो (Spring, .NET DI) |
Trade-offs
text
✓ Testable (inject fakes/mocks) ✓ Swappable implementations
✓ Explicit dependencies ⚠️ More wiring; indirection can obscure flow
⚠️ DI containers add "magic" → harder to trace what's wired where
महत्व
DI हा Dependency Inversion Principle चा व्यावहारिक अमलीकरण आहे — उच्च-स्तरीय लॉजिक कंक्रिट, निम्न-स्तरीय क्लासेसवर अवलंबून राहणे थांबवते.
याचा लाभ म्हणजे testability आणि लचकपणा: तुम्ही टेस्टमध्ये fake डेटाबेस किंवा प्रोडक्शनमध्ये payment provider बदलू शकता - बिজनेस लॉजिक न बदलता, फक्त wiring बदलून.
