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.
The dependency injection pattern has four main roles which are performed by separate classes:
Car
will use the classes Wheel
and Interior
every time.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