Dependency Injection with ASP.NET Core 1.0

Thursday Jun 16th 2016

Achieve more flexibility and decoupling through the use of dependency injection.

By Sudha Polapragada


Dependency is an object that can be used and an injection is the passing of that dependency to a dependent object that would use it. 'Dependency Injection' is a design pattern and, as the name suggests, it is taking a dependency and injecting into a client or caller and it implements inversion of control. Using this pattern, a developer injects dependencies into objects instead of objects creating their own dependencies. This way, more flexibility and decoupling can be achieved.

Most of the applications using MVVM or MVC or other design patterns use DI and use constructor injection in many cases by passing the view model to view at the constructor level. That way, you can maintain the view's code free of any view model logic being coded in it. One more example is that you can decouple the data source connection dependency from the repository class that fetches data from database by passing a connection string as dependency, thus allowing data source to work with any repository by taking the connection string that is sent by caller. Here, the control is inverted by handing the responsibility of creating the connection from the repository class to the caller.

Most of the ASP.NET developers would have implemented DI using one or more of the following approaches:

  • Constructor injection: Injects the dependency at the constructor level.
  • Parameter injection: Injects the dependency at the parameter level.
  • Setter injection: Injects the dependency at the property level.
  • Interface injection: Injects the dependency at the interface level.

There is some confusion among developers about when to use which injection, and it depends on situation. If the injected object is used by more than one method in the class, the constructor level injection is the most appropriate because dependency is resolved one time at the constructor level but, if the dependency is used only by one method, parameter injection is preferred. But, in some situations, the class depends on another class but also can work without it. For example, in logging purposes, a class can work without logging, but it can write logs if you define dependencies as public properties. Dependency Injection is for objects that have complex dependencies. Controllers, services, adapters, and repositories are the kind of objects that can be added to DI. Static access to services and HttpContext are not good practice.

Sample constructor injection code can be as shown below, where the employee repository is injected at the constructor level and is resolved one time. However, it can be used many times in the class methods.

public class EmpAppService
   private IEmpRepository _empRepository;

   public EmpAppService(IEmpRepository empRepository)
      _empRepository = empRepository;

   public void CreateEmp(string name, DateTime Date)
      var Emp = new Emp { Name = name, DOB= dob};

There are many dependency injection frameworks that automate resolving dependencies. This article focuses on dependency injection implementation details using ASP.NET Core 1.0. If you design an application to use DI, it's helpful to have a class dedicated to creating these classes with their associated dependencies. These are known as Inversion of Control (IoC) containers or Dependency Injection (DI) containers. A container is responsible for providing instances of types that are requested from it.

ASP.NET Core 1.0 has a built-in container that supports constructor injection by default.

ASP.NET's container refers to the types that are managed by ASP.NET Core's IoC container. A built-in container's services can be configured in the ConfigureServices method in the application's Startup class. You can use it everywhere DI with ASP.NET Core 1.0. The first step is to use Framework-Provided Services. ASP.NET Core 1.0 introduces a new method, called ConfigureServices, in the Startup class. Once you know the list of service you have to use in the application, you can define the IServiceCollection and then add those services the collection and input that to the ConfigureServices method.

We can define sample service as follows:

public class EmpService : IEmpService
   public IEnumerable< Employee> GetEmployees ()
      return new List< Employee >
         new Employee { FirstName = "John",
            LastName = "King" . Age = 20},
         new Employee { FirstName = "Spencer",
            LastName = "Jr" . Age = 6},
         new Employee { FirstName = "Linda",
            LastName = "Ko" . Age = 50},
public interface IEmpService
   IEnumerable<Employee> GetEmployees();
public class Employee
   public string FirstName { get; internal set; }
   public string LastName { get; internal set; }
   public long Age { get; internal set; }

The next step is to add the service to the DI container. An ASP.NET service can be configured with three main registration options, as shown in the next sections.


If you need to create a service each time it is requested, Transient lifetime is the best option. This mostly suits stateless services. Mapping is done between the interface and concrete type and, due to this new instance, is created every time it is requested. To register EmpService to Service Collection, you can use the following syntax.

services.AddTransient<IEmpService, EmpService>();
services.AddTransient(typeof (IEmpService),
   typeof (EmpService));
services.Add(new ServiceDescriptor(typeof(IEmpService),
   typeof(EmpService), ServiceLifetime.Transient));
services.Add(new ServiceDescriptor(typeof(IEmpService),
   p => new EmpService(), ServiceLifetime.Transient));


If you need to create new instance once per request, the Scoped life time can be used.

services.AddScoped<IEmpService, EmpService>();
services.Add(new ServiceDescriptor(typeof(IEmpService),
   typeof(EmpService), ServiceLifetime.Scoped));
services.Add(new ServiceDescriptor(typeof(IEmpService),
   p => new EmpService(), ServiceLifetime.Scoped));


If the application requires singleton behavior, Singleton lifetime services can be used because the new instance is created the first time it is requested and then every subsequent request will use the same instance.

services.AddSingleton<IEmpService, EmpService>();
services.Add(new ServiceDescriptor(typeof(IEmpService),
   typeof(EmpService), ServiceLifetime.Singleton));
services.Add(new ServiceDescriptor(typeof(IEmpService),
   p => new EmpService(), ServiceLifetime.Singleton));

An instance also can be directly added to the services container. In such scenarios, this instance will be used for all subsequent requests for Singleton-scoped instances. Singleton service is lazy-loaded the first time it is requested, whereas the Instance service is created in ConfigureServices.

You can crate extension method to the IServiceCollection and register multiple services used in the application in MVC. All services needed by MVC middleware are added by the following extension.


We can define extensions as shown in this next code snippet:

public static class ServiceCollectionExtensions
   public static IServiceCollection RegisterServices(
      this IServiceCollection services)
      services.AddTransient<IService1, Service1>();
      services.AddTransient<IService2, Service2>();
      services.AddTransient<IService3, Service3>();
      // you can add all services used in application here
      return services;

Pass this services list to the ConfigureServices method to register them, as shown below.

public void ConfigureServices(IServiceCollection

If you want to replace the built-in container with their preferred container, the ConfigureServices signature can be changed to return IServiceProvider; a different container can be configured and returned. There are many IOC containers available for .NET; some of them are listed below:

  • Spring Framework: This framework offers Dependency Injection and a number of other capabilities.
  • PicoContainer: Tightly focused DI container framework.
  • HiveMind: Another DI container framework.
  • XWork: This is a command pattern framework that very effectively leverages Dependency Injection.
  • Autofac: Autofac is an addictive DI container for .NET 4.5, Silverlight 5, Windows tore apps, and Windows Phone 8 apps.

To add the third-party container, we have to add the appropriate container package(s) to the dependencies property in project.json as demonstrated below:

"dependencies" : {
   "Autofac": "4.0.0-rc2-237",

We then have to configure the container in ConfigureServices and return an IServiceProvider:

public IServiceProvider
   ConfigureServices(IServiceCollection services)
   // add other framework services
   // Add Autofac
   var containerBuilder = new ContainerBuilder();
   var container = containerBuilder.Build();
   return container.Resolve<IServiceProvider>();


I hope this post gives you knowledge on the DI, a built-in container for DI in ASP.NET Core 1.0, how it works, and about using third-party containers with it.

About the Author

About the Author

Sudha Polapragada works as a Lead Developer with a Government Agency. She spent lots of her programming years working as an ASP.NET programmer and with Microsoft Technologies. She also specializes in Oracle and the Microsoft BI suite. In her free time, she explores features on various development platforms, including various database, front-end technologies, Big Data, and cloud technologies.

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved