How to implement the dependency injection pattern in C#
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:
- Service: Service classes are those which are frequently used by another class. For example, the class
Carwill use the classesWheelandInteriorevery time. - Consumer: The consumer class consumes services; it is also known as a client.
- 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.
- Injector: The main class which instantiates a service and injects it into the consumer.
UML diagram
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());}}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved