Chronicling the Adventure that is software Development

Month: December 2016

What is Dependancy Injection?

The type of Dependency Injection ill be looking at today can be categorized as “Constructor Injection”. The idea is that we will inject the needed classes into the constructor, rather than creating or instantiating new objects, thus achieving loose coupling between objects.

When classes are designed with DI in mind, they are more loosely coupled because they do not have direct, hard-coded dependencies on their collaborators. This follows the Dependency Inversion Principle, which states that “high level modules should not depend on low level modules; both should depend on abstractions.” Instead of referencing specific implementations, classes request abstractions (typically interfaces) which are provided to them when the class is constructed. Extracting dependencies into interfaces and providing implementations of these interfaces as parameters is also an example of the Strategy design pattern.
– MS Docs

Dependency Injection is setup in the ConfigureServices method of Startup.cs
This ConfigureServices method is responsible for setting the things that can be injected into our constructors.

In this example I will focus on setting up DB Contexts. To learn more about registering your own services check out Microsoft’s docs here.

Creating a New ASP.NET Core Web Application

When you create a new ASP.NET Core Web Application with Authentication your ConfigureServices method and appsetting.json are set up automatically for you. This is a good place to start. You will see that AddDBContext() is in ConfigureServices and the connection string is stored in appsettings.json. It should look something like this…

This is great, and if it is a part of a new web application, then migrations is auto setup for you. But what if you have another database that you want to build a model for, set up its context, then inject into your controllers…

Injecting an existing DB and DB Context

If you would like to learn how to “reverse engineer” your database tables into a c# model, check out this post.

If you ran the linked above “scaffold” command to create your model and context, you will see that the connection string is set in the OnConfiguring() method or you new context.

At this point everything should build!!
We now have the new context setup and ready to inject into a controller. The last step is very easy, just add our new service to ANY controller’s constructor, here is simple example.