In which scenarios to use Static DI vs Dynamic DI ?
Loading
In which scenarios to use Static DI vs Dynamic DI ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Jan 20, 2025, 4:45 PM
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).
The
Loggerclass can inject different logging strategies dynamically:The
LogStrategycan be dynamically chosen based on the environment or configuration at runtime:the
LogStrategydependency is injected dynamically based on the environment, allowing for flexibility.Tuhin PaulPosted Jan 20, 2025, 4:43 PM
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.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.