Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dependency Injection Carolyn Schroeder May 16, 2017.

Similar presentations


Presentation on theme: "Dependency Injection Carolyn Schroeder May 16, 2017."— Presentation transcript:

1 Dependency Injection Carolyn Schroeder May 16, 2017

2 What is Dependency Injection
Good software design dictates that a class should not create instances of its dependencies. Instead the dependencies should be injected into the class.

3 Suppose we are designing a car class. A car needs tires
What does this mean? Suppose we are designing a car class. A car needs tires Our first approach would be instantiate a new set of tires in the car constructor

4 What would this look like?
public class Car { private Firestone _tires; public Car() _tires = new Firestone(); }

5 The car class is brittle
What’s wrong with this? The car class is brittle What if you want to put a new brand of tires on your car? You are locked into the brand you instantiated This is called tight coupling

6 Loose Coupling If the tires are supplied to the car constructor the brand doesn’t matter All the car needs to do is use the tires to run In other words all the class needs is a tire interface. If it acts like a tire, the car know how to use it

7 What would this look like?
public class Car { private ITires _tires; public Car(ITires tires) _tires =tires }

8 Dependency Injection in MVC
Dependency Injection in MVC typically means injection into a controller But out of the box MVC controllers (before .NET Core) only allow constructors without parameters

9 How do I get started with controller injection?
An Inversion of Control Container or IoC Container is used to supply a class with its dependencies We will use Unity as an IoC Container for our MVC application To install Unity, run Install-Package Unity.Mvc5 in the Package Manager Console

10 Nice, but why should I care?
Typically a repository get its data from the database For unit testing, it is necessary to mock the repository to return some fake data With dependency injection, we can inject the mock repository into the controller

11 Resources DependencyInjection solution is on GitHub: ion PowerPoint slides can be downloaded from my site:


Download ppt "Dependency Injection Carolyn Schroeder May 16, 2017."

Similar presentations


Ads by Google