DependencyinjectionMVC.md - brainchildservices/curriculum GitHub Wiki

SLIDE-1

DEPENDENCY INJECTION

Dependency Injection is a design pattern, a technique that helps to inject dependent object of a class without changing the concrete implementation.

SLIDE-2

First let’s understand what a dependency in programming means.

  • When class A uses some functionality of class B, then its said that class A has a dependency of class B.
  • In C#, before we can use methods of other classes, we first need to create the object of that class (i.e. class A needs to create an instance of class B).
  • So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.

image

SLIDE-3

Why should use dependency injection?

  • Let’s say we have a car class which contains various objects such as wheels, engine, etc.
  • Here the car class is responsible for creating all the dependency objects. Now, what if we decide to ditch MRFWheels in the future and want to use Yokohama Wheels?
  • We will need to recreate the car object with a new Yokohama dependency. But when using dependency injection (DI), we can change the Wheels at runtime (because dependencies can be injected at runtime rather than at compile time).
  • You can think of DI as the middleman in our code who does all the work of creating the preferred wheels object and providing it to the Car class.
  • It makes our Car class independent from creating the objects of Wheels, Battery, etc.

SLIDE-4

There are many ways you can inject dependency to a class. For example:

SLIDE-5

Task

Suppose your Client class needs to use two service classes, Implement Dependency injection using Constructor Injection. Use IService as Interface name

Hints:-

  1. This is a widely used way to implement DI.
  2. Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when creating the instance of that class.
  3. Injected component can be used anywhere within the class.
  4. Recommended to use when the injected dependency, you are using across the class methods.
  5. It addresses the most common scenario where a class requires one or more dependencies.