Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dependency
injection
design
pattern
solid

How to implement the dependency injection pattern in C#

Educative Answers Team

Any code in which a class depends explicitly on another class is a highly-coupled code. The dependency injection pattern, like other design patterns, aims to lower the coupling (dependency) in a program so that it is easily extendable.

Parts of the pattern

The dependency injection pattern has four main roles which are performed by separate classes:

  1. Service: Service classes are those which are frequently used by another class. For example, the class Car will use the classes Wheel and Interior every time.
  2. Consumer: The consumer class consumes services; it is also known as a client.
  3. Interface: This is the interface that is implemented by every service. Introducing this interface reduces dependency between a consumer and the services it utilizes. Moreover, it increases the flexibility of our code.
  4. Injector: The main class which instantiates a service and injects it into the consumer.

UML diagram

svg viewer

Implementation

using System;

// Service interface:
interface IService{
  string getName();
}

// First implementation of IService:
class SlowService: IService{
  private string name = "Slow service";
  public string getName(){
    return name;
  }
}

// Second implementation of IService:
class FastService: IService{
  private string name = "Fast service";
  public string getName(){
    return name;
  }
}

// Consumer class:
class Consumer{
  private IService myService;
  public Consumer(IService s){
    myService = s;
  }
  public IService getService(){
    return myService;
  }
}

// Injector/Main class:
class Injector{
  static void Main(string[] args){
    Consumer x = new Consumer(new SlowService());
    Console.WriteLine(x.getService().getName());

    Consumer y = new Consumer(new FastService());
    Console.WriteLine(y.getService().getName());
  }
}

RELATED TAGS

dependency
injection
design
pattern
solid
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring