Design Patterns

Example 3: Dependency Injection with Framework (ASP.NET Core)

In ASP.NET Core, DI is built into the framework, making it easy to inject dependencies across controllers, services, and middleware:

Startup Configuration (ASP.NET Core)

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Register services with DI container
        services.AddScoped();
        services.AddScoped, UserRepository>();
        services.AddScoped();

        // Other service registrations
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configuration and middleware setup
    }
}

Controller Example (ASP.NET Core)

public class UserController : ControllerBase
{
    private readonly UserService _userService;

    // Constructor Injection in ASP.NET Core Controller
    public UserController(UserService userService)
    {
        _userService = userService;
    }

    [HttpPost("register")]
    public IActionResult Register([FromBody] UserDto userDto)
    {
        // Convert UserDto to User
        User user = new User { Name = userDto.Name };

        // Use UserService with injected dependencies
        _userService.RegisterUser(user);

        return Ok("User registered successfully");
    }
}

Summary

Dependency Injection is a design pattern that promotes loose coupling between classes by allowing dependencies to be injected rather than hard-coded or instantiated within the dependent class. It enhances modularity, testability, and maintainability of software systems, making it a widely adopted practice in modern software development.

Dependency Injection in C# improves code maintainability, testability, and flexibility by decoupling dependencies from the classes that use them. Whether implemented manually or using a DI framework like ASP.NET Core's built-in container, DI promotes modular and scalable software design practices. It allows for easy switching of implementations, facilitates unit testing with mock objects, and enhances the overall quality of software systems.