Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 20, 2025, 11:43 AM EST
In Static DI, dependencies are resolved and injected at compile time, meaning the container or framework knows about the dependencies at the time the application is compiled. The DI container predefines which services and objects should be injected into the class at the time of class instantiation.
How Static DI Works:
Use Case:
Real-time Scenario for Static DI:
Consider a payment processing system for an e-commerce platform. The system uses static DI to inject a payment service into a
PaymentController.class PaymentController { private final PaymentService paymentService; public PaymentController(PaymentService paymentService) { this.paymentService = paymentService; } public void processPayment() { paymentService.process(); } }Here,
PaymentServiceis injected at the time thePaymentControlleris instantiated (via static DI) and is pre-defined. The payment method (e.g., credit card, PayPal) remains fixed during the runtime, so static DI is a good fit.Tuhin PaulRank #7 · 71.9K reputationPosted Jan 20, 2025, 11:45 AM EST
In Dynamic DI, dependencies are resolved at runtime, allowing more flexibility in how dependencies are injected. The DI container is responsible for resolving and injecting dependencies when an object is needed, and the dependencies can change based on the environment or configuration at runtime.
How Dynamic DI Works:
Use Case:
Real-time Scenario for Dynamic DI:
Imagine a logging framework where you want to use different logging strategies based on the environment (e.g., development, production).
class Logger { private final LogStrategy logStrategy; public Logger(LogStrategy logStrategy) { this.logStrategy = logStrategy; } public void log(String message) { logStrategy.logMessage(message); } }The
Loggerclass can inject different logging strategies dynamically:The
LogStrategycan be dynamically chosen based on the environment or configuration at runtime:class LogStrategyFactory { public static LogStrategy getLogStrategy(String environment) { if (environment.equals("development")) { return new ConsoleLogStrategy(); } else { return new FileLogStrategy(); } } }the
LogStrategydependency is injected dynamically based on the environment, allowing for flexibility.