- Hosting Article & Tutorial

ASP.NET MVC Hosting Tutorial – How To Use Dependency Injection

How To Use Dependency Injection in ASP.NET MVC – ASP.NET MVC 6 comes with a basic dependency injection container that will allow you to implement constructor and property dependency injection into your controller classes. This may be enough for smaller ASP.NET MVC 6 applications while other applications can continue to use Autofac, Ninject, StructureMap, Unity, etc. In this tutorial, we will learn how to use dependency injection in ASP.NET MVC. There is a lot more to dependency injection, this post gives you a quick tutorial to the basics of registering services and injecting those services into your ASP.NET MVC 6 Controllers.

How To Use Dependency Injection in ASP.NET MVC 6

The key to dependency injection in ASP.NET MVC 6 is to register your services in the Startup File’s ConfigureServices Method. Here is an example of registering a TestService:

One can declare services as one of 4 types:

  • Instance
    A specific instance is given all the time. You are responsible for its initial creation.
  • Transient
    A new instance is created every time.
  • Singleton
    A single instance is created and it acts like a singleton.
  • Scoped
    A single instance is created inside the current scope. It is equivalent to Singleton in the current scope.

Once you have registered the new service with the dependency injection container in ASP.NET MVC 6 you can either inject the service into the constructor of a controller class or the property of a controller class. In this example the service is injected into the constructor of the controller class:

In this example the service is injected into the property of the controller class. Notice the “FromServices” Attribute on the property.

If you looking for ASP.NET MVC 6 hosting, find out our recommendation here.