0
0
CsharpHow-ToBeginner · 4 min read

How to Use Dependency Injection in C# - Simple Guide

In C#, dependency injection means giving an object the things it needs instead of creating them inside. You do this by defining interfaces and passing implementations through constructors or methods, often using a DI container like Microsoft.Extensions.DependencyInjection.
📐

Syntax

Dependency injection in C# typically uses constructor injection. You define an interface for the service, implement it, and then pass the implementation to the class that needs it via the constructor.

This keeps classes independent and easy to test.

csharp
public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve()
    {
        Console.WriteLine("Service Called");
    }
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start()
    {
        _service.Serve();
    }
}
💻

Example

This example shows how to use Microsoft's built-in dependency injection container to inject a service into a client class and run it.

csharp
using System;
using Microsoft.Extensions.DependencyInjection;

public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve()
    {
        Console.WriteLine("Service Called");
    }
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start()
    {
        _service.Serve();
    }
}

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();
        services.AddTransient<IService, Service>();
        services.AddTransient<Client>();

        var provider = services.BuildServiceProvider();

        var client = provider.GetService<Client>();
        client.Start();
    }
}
Output
Service Called
⚠️

Common Pitfalls

  • Not registering services in the DI container causes runtime errors.
  • Using concrete classes directly instead of interfaces reduces flexibility.
  • Creating service instances manually inside classes defeats the purpose of DI.
  • Forgetting to use readonly for injected dependencies can lead to accidental reassignment.
csharp
/* Wrong way: creating service inside class */
public class BadClient
{
    private IService _service = new Service(); // tightly coupled
}

/* Right way: inject service via constructor */
public class GoodClient
{
    private readonly IService _service;
    public GoodClient(IService service)
    {
        _service = service;
    }
}
📊

Quick Reference

Tips for using Dependency Injection in C#:

  • Always program to interfaces, not concrete classes.
  • Register all services in the DI container before use.
  • Use constructor injection for mandatory dependencies.
  • Use Microsoft.Extensions.DependencyInjection for a simple built-in DI container.
  • Keep injected dependencies readonly to avoid accidental changes.

Key Takeaways

Use constructor injection to pass dependencies via interfaces for loose coupling.
Register all services in a DI container like Microsoft.Extensions.DependencyInjection.
Avoid creating dependencies inside classes to keep code testable and flexible.
Mark injected dependencies as readonly to prevent accidental reassignment.
Programming to interfaces improves maintainability and allows easy swapping of implementations.