Constructor Injection
Dependencies are provided through a class constructor.
Dependency Injection (DI) is a design pattern and a form of Inversion of Control (IoC) where an object receives its dependencies from an external source rather than creating them itself. DI promotes loose coupling, testability, and modularity.
Constructor Injection
Dependencies are provided through a class constructor.
Setter Injection
Dependencies are provided through setter methods.
Interface Injection
Dependencies are provided through an interface method.
// Constructor Injection@Servicepublic class UserService { private final UserRepository userRepository;
@Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; }}
// Setter Injection@Servicepublic class UserService { private UserRepository userRepository;
@Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; }}// Constructor Injectionpublic class UserService{ private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository) { _userRepository = userRepository; }}
// Registering Dependencies in Startup.cspublic void ConfigureServices(IServiceCollection services){ services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<UserService>();}// Constructor Injection@Controller('users')export class UserController { constructor(private userService: UserService) {}
@Get() findAll() { return this.userService.findAll(); }}
// Registering Dependencies in a Module@Module({ providers: [UserService, UserRepository], controllers: [UserController],})export class AppModule {}| Pros | Cons |
|---|---|
| Reduces coupling between components | Can introduce complexity if overused |
| Makes applications more testable and modular | Requires learning a DI framework or container |
| Easier to swap implementations | Can lead to “magic” behavior if not used carefully |