Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Using Dependency Injection7:55 with James Churchill
Let's see how we can update our controller to use constructor injection to declare its dependencies. And let's install a DI container to handle creating object instances and managing the lifetime of those instances.
To follow along committing your changes to this course, you'll need to fork the aspnet-fitness-frog-spa repo. Then you can clone, commit, and push your changes to your fork like this:
git clone <your-fork> cd aspnet-fitness-frog-spa git checkout tags/v3.1 -b using-dependency-injection
DI Container Configuration Overview
After installing the
SimpleInjector.Integration.WebApi.WebHost.QuickStart NuGet package, you'll have a new file in your project's App_Start folder: SimpleInjectorWebApiInitializer.cs. Let's walkthrough the code in that file.
The attribute at the top of the file is using a package called WebActivator to wire up the SimpleInjectorWebApiInitializer
Initialize method to be called right after the
Application_Start method has completed. By using this method, Simple Injector avoided having to modify our project's
Application_Start method in the Global.asax.cs file. For more information about WebActivator, see github.com/davidebbo/WebActivator.
Initialize method instantiates and initializes our DI container. The first line of code instantiates the Simple Injector container.
var container = new Container();
The second line of code sets the default scoped lifestyle for our container.
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
Unfortunately, this code uses a deprecated class for the default scoped lifestyle. While this doesn't generate a compilation error, it'll generate a warning. To eliminate the warning, you can optionally update this line of code to:
container.Options.DefaultScopedLifestyle = new SimpleInjector.Lifestyles.AsyncScopedLifestyle();
There are a number of scoped lifestyle types available. It's important to use the one that best suites your application type. For Web API, you want to use the AsyncScopedLifestyle type. That's what this line of code is doing—it's setting the default scoped lifestyle for our DI container to the AsyncScopedLifestyle type.
InitializeContainer method is called, passing in the DI container.
InitializeContainer method is defined just below the
Initialize method. The
InitializeContainer method is where we'll configure the dependencies for our application.
Then a method on the DI container—
RegisterWebApiControllers—is called, which registers all of our application's API controllers as dependencies.
Verify method is called to verify the configuration of the DI container.
If any configuration errors are found, and exception will be thrown. Then Web API's dependency resolver is set to an instance of the SimpleInjectorWebApiDependencyResolver class.
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
The dependency resolver is responsible for locating dependencies in the DI container. For example, when the DI container is instantiating an instance of the EntriesRepository class, it'll detect that it needs an instance of the Context class to pass to the EntriesRepository's class constructor. The dependency resolver will be used to resolve the Context class dependency to an instance of that class contained within the DI container.
Not only is the dependency resolver used to resolve dependencies between our classes, but it's also used by Web API to resolve controller dependencies. Once Web API has mapped a route to a specific controller, it'll ask the dependency resolver for an instance of that controller class. That's why it was necessary to register our controllers with the DI container.
As we saw on the first section of this course,
our Visual Studio solution contains a shared class library project
that contains entity framework related classes.
These classes, a database context, entities, and repositories
can be used within the FitnessFrog API to persist data to a database.
Let's update the entries controller class to make use of these classes.
Within our entries controller class, we need an instance of the entries repository
class, which in turn needs an instance of the contents class.
We could say that the entries controller class
has a dependency on the entries repository class.
And the entries repository class has a dependency on the context class.
Let's start with adding a private field for the entries repository.
private EntriesRepository, add a using directive,
the Treehouse.FitnessFrog.Shared.Data namespace.
Name the private field, entriesRepository, and set its values to null.
Then add a constructor for the EntriesController.
Then update the constructor to instantiate an instance of the context class.
And the EntriesRepository class, passing in an instance of the context.
This approach is a workable solution, but it does have a couple of drawbacks.
First, our implementation is incomplete.
We need to add code to manage the lifetime of the data based context.
We can do that by overriding the baseclasses virtual dispose method,which
will give us a hook for calling the dispose method on our context class.
Second, we're directly instantiating both the context and
entriesRepository classes, which tightly couples those classes with our controller.
This will make unit testing our controller more difficult than it needs to be.
Ideally, what we want to be able to do
is to add our dependencies as parameters to our constructor, like this.
EntriesRepository entriesRepository, and
remove the instantiation of the context class.
And replace the instantiation of the EntriesRepository class with the reference
to the parameter.
By adding an EntriesRepository parameter to our constructor,
we're declaring that this class has a dependency on the EntriesRepository.
Where the EntriesRepository instance comes from, and
how it's instantiated shouldn't be a concern of the EntriesController class.
Handling dependencies in this manner,
by using constructor parameters, is known as constructor injection.
Constructor injection is an implementation of a broader design pattern
known as dependency injection.
Overall, dependency injection requires less code, and
offers an elegant and flexible solution for managing dependencies between classes.
If you're not familiar with dependency injection and they're be related
inversion of control design principle, see the teacher's notes for more information.
So, what instantiates the instance of the EntriesRepository class
that is being passed to our controller's constructor?
And what instantiates the instance of the contest class
that the entry's repository class is dependent upon?
We need to install and
configure a dependency injection container, or DI container, for short.
The DI container is responsible for creating object instances and
managing the lifetime of those instances.
There are a number of DI libraries available for .NET.
For our project, we'll be using the Simple Injector DI library.
We can use the NuGet package manager to install Simple Injector.
Simple Injector provides a quick start package
that will not only add the required assembly reference to our project, but
will add the code that we need to configure the DI container for web API.
To install the necessary Simple Injector package, right click on the project,
and select Manage NuGet Packages.
Click on the Browse tab if it's not already selected.
Then search for simpleinjector.integration.
Here's the SimpleInjector.Integration.WebApi package,
but we're looking for another package.
Here it is.
Once you've found the correct package, go ahead and install it.
Once the package is finished installing,
open the SimpleInjectorWebApiInitializer.cs file
located in the App_Start folder.
The Initialize() method, which is called right after our application is started,
instantiates and initializes our DI container.
For a detailed overview of what the code in this method does,
see the teacher's notes.
We need to update the initialized container method to register the types in
our application that we want the DI container to manage as dependencies.
To do that, we'll use the containers Register method.
When calling a register method, we specify the type that we want to register
as the method's generic type parameter.
Don't forget to add a using statement to the Treehouse.FitnessFrog.Shared.Data
Then we need to pass in a Lifestyle enumeration value.
The provided Lifestyle enum value tells the container how many instances of
a type should be created, and how long each of those instances should leave.
Simple Injector provides three built in lifestyles.
Transient, a new instance is created every time that an instance is requested.
Singleton, only one instance is created per container.
And Scoped, for every request within an implicitly or
explicitly defined scope, a single instance will be returned and
that instance will be disposed when the scope ends.
Setting the lifestyle to Scoped effectively tells the DI container to
create a single instance pre-request.
This means that for any given request,
there'll only be a single instance of the context type.
Now, let's register our other two dependencies.
Entries repository and activities repository.
You need to sign up for Treehouse in order to download course files.Sign up