Bird
Raised Fist0
LLDsystem_design~7 mins

Dependency injection framework in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When components in a software system create or find their own dependencies, it leads to tightly coupled code that is hard to test, maintain, and extend. This causes difficulties in swapping implementations, increases bugs during changes, and slows down development.
Solution
A dependency injection framework automatically provides components with their required dependencies from a central place. Instead of components creating dependencies themselves, the framework injects them, allowing loose coupling and easier testing by substituting dependencies without changing component code.
Architecture
Component
Request
Dependency Injection
Dependency
Dependency

This diagram shows how a component requests dependencies from the dependency injection framework, which then provides the appropriate implementations.

Trade-offs
✓ Pros
Promotes loose coupling by separating dependency creation from usage.
Improves testability by allowing easy substitution of mock dependencies.
Centralizes configuration of dependencies, simplifying management.
Facilitates scalability and maintainability by decoupling components.
✗ Cons
Introduces additional complexity and learning curve for developers.
May obscure the flow of dependencies, making debugging harder.
Can add slight runtime overhead due to dependency resolution.
Use when building medium to large applications with many interdependent components requiring flexibility and testability, typically when the codebase exceeds a few thousand lines or multiple developers work on it.
Avoid in small, simple applications with few dependencies where the overhead of a framework outweighs benefits, or when performance constraints forbid any runtime overhead.
Real World Examples
Google
Uses Dagger, a dependency injection framework, to manage dependencies in Android apps, improving modularity and testability.
Netflix
Employs dependency injection to decouple microservices components, enabling easier testing and faster development cycles.
Spring (Pivotal)
Spring Framework uses dependency injection extensively to manage Java application components, simplifying configuration and promoting loose coupling.
Code Example
The before code shows UserService creating its own Database instance, causing tight coupling. The after code uses a simple DI container to inject the Database instance into UserService, enabling loose coupling and easier testing.
LLD
### Before: Without Dependency Injection Framework
class Database:
    def connect(self):
        return "Connected to database"

class UserService:
    def __init__(self):
        self.db = Database()  # Direct dependency creation

    def get_user(self):
        return self.db.connect()

service = UserService()
print(service.get_user())


### After: With Dependency Injection Framework
class Database:
    def connect(self):
        return "Connected to database"

class UserService:
    def __init__(self, db):  # Dependency injected
        self.db = db

class DIContainer:
    def __init__(self):
        self._services = {}

    def register(self, key, instance):
        self._services[key] = instance

    def resolve(self, key):
        return self._services.get(key)

container = DIContainer()
container.register('db', Database())

service = UserService(container.resolve('db'))
print(service.get_user())
OutputSuccess
Alternatives
Service Locator
Components request dependencies from a central registry explicitly, rather than having them injected automatically.
Use when: Choose when you want explicit control over dependency retrieval and can tolerate tighter coupling.
Manual Dependency Injection
Dependencies are passed manually through constructors or setters without a framework.
Use when: Choose for small projects or when avoiding framework complexity is a priority.
Summary
Dependency injection frameworks prevent tight coupling by providing dependencies externally to components.
They improve testability and maintainability by centralizing dependency management.
They are best suited for medium to large applications where flexibility and modularity are important.

Practice

(1/5)
1. What is the main purpose of a dependency injection framework?
easy
A. To store data permanently on disk
B. To automatically provide parts (dependencies) to your code
C. To make your code run faster by compiling it
D. To write all code manually without any helpers

Solution

  1. Step 1: Understand what dependency injection means

    Dependency injection means giving the parts your code needs automatically instead of creating them inside the code.
  2. Step 2: Identify the role of the framework

    A dependency injection framework helps by managing and providing these parts for you, making your code easier to change and test.
  3. Final Answer:

    To automatically provide parts (dependencies) to your code -> Option B
  4. Quick Check:

    Dependency injection = automatic parts supply [OK]
Hint: Think: Who gives parts to your code? The injector does! [OK]
Common Mistakes:
  • Confusing dependency injection with data storage
  • Thinking it speeds up code execution directly
  • Believing it replaces manual coding completely
2. Which of the following is the correct way to register a service in a dependency injection framework?
easy
A. injector.register(ServiceClass)
B. ServiceClass.inject()
C. register.injector(ServiceClass)
D. ServiceClass.register()

Solution

  1. Step 1: Recall the registration syntax

    In most dependency injection frameworks, you register a service by calling a method on the injector object and passing the service class.
  2. Step 2: Match the correct syntax

    The correct syntax is injector.register(ServiceClass), which tells the injector to manage that service.
  3. Final Answer:

    injector.register(ServiceClass) -> Option A
  4. Quick Check:

    Register service = injector.register() [OK]
Hint: Register services by calling register on the injector [OK]
Common Mistakes:
  • Calling register on the service class instead of injector
  • Mixing method order or names
  • Using non-existent methods like inject() on service
3. Given the code below, what will serviceA.getName() output?
class ServiceA {
  getName() { return 'Service A'; }
}

injector.register(ServiceA);
const serviceA = injector.get(ServiceA);
console.log(serviceA.getName());
medium
A. null
B. undefined
C. Error: Service not found
D. Service A

Solution

  1. Step 1: Understand registration and retrieval

    The code registers ServiceA with the injector, then asks the injector to give an instance of ServiceA.
  2. Step 2: Check the method call on the instance

    The instance has a method getName() that returns the string 'Service A'. So calling serviceA.getName() returns 'Service A'.
  3. Final Answer:

    Service A -> Option D
  4. Quick Check:

    Registered service returns its name [OK]
Hint: Registered services return their methods normally [OK]
Common Mistakes:
  • Assuming injector.get returns undefined or null
  • Forgetting to register before getting
  • Expecting an error without registration
4. Identify the error in the following code snippet using a dependency injection framework:
class ServiceB {}

const serviceB = injector.get(ServiceB);
injector.register(ServiceB);
medium
A. ServiceB is registered after trying to get it
B. ServiceB class is missing a constructor
C. injector.get should be injector.fetch
D. injector.register should be called twice

Solution

  1. Step 1: Check the order of registration and retrieval

    The code tries to get ServiceB from the injector before registering it, which causes an error because the injector doesn't know about ServiceB yet.
  2. Step 2: Confirm correct usage order

    Services must be registered before they can be retrieved from the injector.
  3. Final Answer:

    ServiceB is registered after trying to get it -> Option A
  4. Quick Check:

    Register before get = correct order [OK]
Hint: Always register before getting a service [OK]
Common Mistakes:
  • Trying to get service before registration
  • Confusing method names like get vs fetch
  • Thinking constructor is required for registration
5. You want to inject a Logger service into a UserService using a dependency injection framework. Which approach correctly applies dependency injection to make UserService easier to test?
class Logger {
  log(msg) { console.log(msg); }
}

class UserService {
  constructor(logger) {
    this.logger = logger;
  }
  createUser(name) {
    this.logger.log(`User ${name} created`);
  }
}

injector.register(Logger);
injector.register(UserService);

How should you get UserService with Logger injected?
hard
A. const userService = injector.get(Logger);
B. const userService = new UserService(new Logger());
C. const userService = injector.get(UserService);
D. const userService = UserService();

Solution

  1. Step 1: Understand constructor injection

    UserService expects a Logger instance in its constructor. The injector knows how to create Logger and UserService because both are registered.
  2. Step 2: Use injector to get UserService with dependencies

    Calling injector.get(UserService) lets the injector create UserService and automatically provide Logger to it.
  3. Final Answer:

    const userService = injector.get(UserService); -> Option C
  4. Quick Check:

    Injector provides dependencies via constructor [OK]
Hint: Get the service from injector to auto-inject dependencies [OK]
Common Mistakes:
  • Manually creating dependencies instead of using injector
  • Getting Logger instead of UserService
  • Calling UserService without new keyword