What Is Dependency Injection In C# Programming

Dependency Injection (DI) is a software design pattern that allows a class to receive its dependencies (i.e. objects that it depends on) through its constructor or methods, rather than creating them directly. This makes it easier to test the class and to change the implementation of the dependencies without affecting the class that uses them.

In C#, dependency injection is typically implemented using an Inversion of Control (IoC) container, which is a library that manages the creation and injection of dependencies into classes. The most popular IoC containers for C# are Autofac, Castle Windsor, and Microsoft's own Dependency Injection (DI) framework, which is built into the ASP.NET Core framework.

Here is an example of how dependency injection can be used in C#,

interface ILogger {
    void Log(string message);
}
class ConsoleLogger: ILogger {
    public void Log(string message) {
        Console.WriteLine(message);
    }
}
class MyClass {
    private readonly ILogger _logger;
    public MyClass(ILogger logger) {
        _logger = logger;
    }
    public void DoSomething() {
        _logger.Log("Doing something...");
    }
}

In this example, MyClass depends on an ILogger interface to perform logging. Instead of creating an instance of ConsoleLogger directly, MyClass receives an ILogger instance through its constructor. This allows the application to easily change the implementation of the ILogger interface without affecting MyClass.

This also allows for easy testing, for instance by passing a mock logger object in the constructor and testing how MyClass behaves.

An IoC container would be used to create and wire up these objects for you, so you don't have to new up the objects and pass them around manually.

Continue Reading >> Dependency Injection in C#