Dependency Injection in C#

It is the onus of every software developer to create applications that run smoothly and efficiently and that require little to no maintenance. Further, code for these apps should be well-maintainable and extensible, so that the codebase can be updated to add functionality in later versions and releases.

As developers, it is worth remembering that the more maintainable our code is, the more it can easily be tested and reused. A good practice to make code more maintainable is through the use of dependency injection. Loosely coupled code is always an asset when it comes to code reusability and testing; it is easier for programmers to add new features if the code is well-maintained.

To that end, using dependency injection in your applications makes your code loosely coupled. In this C# programming tutorial, we are covering the concept of dependency injection and how it is used to couple code loosely in C#.

Read: 7 Best C# IDEs

What is Code Dependency in C#?

Code Dependency is an important concept to understand regardless of the programming language you create software in. It can be more readily understood if you think of some component in an application that has a dependency on some other component(s) to accomplish its task. There are even times when the required components may be present in different classes or services within the program.

For example, if class A uses another class or service B, then A is dependent on B to accomplish its task. In such cases, both components (A and B) are said to be coupled together. This coupling may either be loosely-coupled or tightly coupled. Components that depend heavily on other components are considered tightly coupled, while those that are less dependent would, in turn, fall under the umbrella of loosely coupled.

The more the code has a dependency on other components, the less the code will be reusable. If the components are coupled loosely, then we can reuse the code more effectively. And, to achieve the goal of loosely-coupled code dependency, we use dependency injection (DI).

What Is Dependency Injection In C#?

To understand dependency injection properly, we have to first understand the concepts of dependency inversion and inversion of control (IoC).

The concept of dependency inversion states that high-level modules should depend on abstraction, rather than on low-level modules.

Inversion of control enables programmers to change the normal flow of programming. It helps in reducing code dependency. Inversion of control transfers the control of the object to a framework and that framework, in turn, will have the responsibility to resolve the dependencies among different modules and classes at runtime.

DI helps programmers to write loosely coupled code and helps reduce the tight coupling of code among components. DI further enables developers to achieve less coupling among components and thus contributes to writing readable, maintainable code. It also makes the code more flexible, which in turn, makes it easy to test the code, find errors, and resolve bugs.

One of the major advantages of dependency injection is that it enables developers to reduce the tight coupling of modules and components among other components. It also makes the code more reusable and makes it easy to test applications. Lastly, it changes the workflow of an application by reducing the amount of code being written for commonly executed tasks.

Read: Dependency Injection versus Inversion of Control

How to implement Dependency Injection in C#

There are three ways you can use the dependency injection pattern in your C# applications. They are:

  • Constructor Injection
  • Property (or Setter) Injection
  • Method Injection

Examples of C# Dependency Injection

Below, we will learn about each type of dependency injection in detail.

What is Constructor Injection in C#?

Constructor injection is one of the most widely used methods for implementing dependency injection when developing applications. By using constructor dependency injection, you can inject the dependent class object through the constructor. The injected component can then be used anywhere across different class methods.

Let’s get our hands dirty and understand it through the following code example, which shows how to implement constructor injection in C#:

public class EmployeeBusinessLogic
{
    IEmployeeDataAccess _dataAccess;

    public EmployeeBusinessLogic(IEmployeeDataAccess empDataAccess)
    {
        _dataAccess = empDataAccess;
    }

    public EmployeeBusinessLogic()
    {
        _dataAccess = new EmployeeDataAccess();
    }

    public string ProcessEmployeeData(int id)
    {
        return _dataAccess.GetEmployeeName(id);
    }
}

public interface IEmployeeDataAccess
{
    string GetEmployeeName(int id);
}

public class EmployeeDataAccess: IEmployeeDataAccess
{
    public EmployeeDataAccess()
    {
        //
    }

    public string GetEmployeeName(int id) 
    {
        //fetch the employee name from the database        
        return "Employee Name: John"; 
    }
}

The above C# code demonstrates dependency injection through the constructor by passing a parameter of type IEmployeeDataAccess in the DataBusinessLogic constructor. By doing so, we can inject an object of IEmployeeDataAccess into the calling class EmployeeService, as depicted in the following code snippet:

public class EmployeeService
{
    EmployeeBusinessLogic _empBL;

    public EmployeeService()
    {
        _ empBL = new EmployeeBusinessLogic(new EmployeeDataAccess());
    }

    public string GetEmployeeName(int id) {
        return _empBL.ProcessEmployeeData(id);
    }

}

As you can see in the above code, the EmployeeService class creates and injects the EmployeeDataAccess object into the EmployeeBusinessLogic class.

Note that there is no need to create an object of EmployeeDataAccess using the factory method or using the new keyword in the EmployeeBusinessLogic class. The calling class creates and sets the EmployeeDataAccess class to the EmployeeBusinessLogic class. In this way, these two classes (EmployeeBusinessLogic and EmployeeDataAccess) become loosely coupled.

Read: The Repository Design Pattern in C#

What is Property Injection in C#?

Property injection is the process of injecting dependent class objects through the property. It is the preferred method when a class has optional dependencies, as dependency can be injected without changing the object state.

Let’s review a code example showing how to implement property injection in C#:

public class EmployeeBusinessLogic
{
    public IEmployeeDataAccess dataAccess { get; set; }
    public EmployeeBusinessLogic()
    {
    }

    public string GetEmployeeName(int id)
    {
        return dataAccess.GetEmployeeName(id);
    }
}

public class EmployeeService
{
    EmployeeBusinessLogic _ empBL;

    public EmployeeService()
    {
        _ empBL = new EmployeeBusinessLogic();
        _ empBL.dataAccess = new EmployeeDataAccess();
    }

    public string GetEmployeeName(int id) {
        return _empBL.GetEmployeeName(id);
    }
}

As you can see in the above C# code example, the EmployeeBusinessLogic class contains a public property named dataAccess, in which you can set an instance of the class IEmployeeDataAccess.

In the EmployeeService class, you can make use of this public property to create – and set – the EmployeeDataAccess class.

What is Method Injection in C#?

Next, we have the method known as method injection. Method injection is the process used to inject the dependent class object through methods. With method injection, the dependency can be injected into a specific class method and is then used when the whole class does not require dependency.

To better understand this, let’s examine some sample code showing how to implement method injection in C#:

interface IDataAccessDependency
{
    void SetDependency(IEmployeeDataAccess employeeDataAccess);
}

public class EmployeeBusinessLogic : IDataAccessDependency
{
    IEmployeeDataAccess _dataAccess;

    public EmployeeBusinessLogic()
    {
    }

    public string GetEmployeeName(int id)
    {
        return _dataAccess.GetEmployeeName(id);
    }
        
    public void SetDependency(IEmployeeDataAccess empDataAccess)
    {
        _dataAccess = empDataAccess;
    }
}

public class EmployeeService
{
    EmployeeBusinessLogic _empBL;

    public EmployeeService()
    {
        _empBL = new EmployeeBusinessLogic();
        ((IDataAccessDependency)_empBL).SetDependency(new EmployeeDataAccess());
    }

    public string GetEmployeeName(int id) {
        return _empBL.GetEmployeeName(id);
    }
}

In the above example, the EmployeeBusinessLogic class implements the interface IDataAccessDependency, which has a function named SetDependency(). The class EmployeeService uses this method to inject the dependent class into the client class.

Read: Debugging Tools for C#

Conclusion to Dependency Injection in C#

So far, we have seen what dependency injection is and how you can implement this design pattern in C# to create loosely coupled classes. In a real-world software application, there may be components that have dependencies on other components. For any programmer, this can be a tedious and time-consuming task to manage those components effectively. In such a situation, dependency injection helps the developer to change the workflow of the software application and create loosely-coupled code.

Read more C# programming tutorials and developer tool reviews.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Must Read