ASP.NET Core Dependency Injection

alirıza adıyahşi
Jun 2, 2017 · 8 min read
Image for post
Image for post

In this article, I won’t explain what is dependency injection (DI). I will try to explain how DI in ASP.NET Core works what can we do with it and how we can use other DI containers (Autofac and Castle Windsor) with ASP.NET Core.ASP.NET Core provides a minimal feature set to use default services cotainer. But you want to use different DI containers, because DI in ASP.NET Core is vey primitive. For example, it dosn’t support property injection or advanced service registering methods.

Let’s go to the examples and try to understand basics of DI in ASP.NET Core.

IServiceCollection is the collection of the service descriptors. We can register our services in this collection with different lifestyles (Transient, scoped, singleton)

IServiceProvider is the simple built-in container that is included in ASP.NET Core that supports constructor injection by default. We are getting regisered services with using service provider.

Service Lifestyle/Lifetimes

We can configure services with different types of lifestyles like following.


This lifestyle services are created each time they are requested.


Scoped lifestyle services are created once per request.


A singleton service is created once at first time it is requested and this instance of service is used by every sub-requests.

Let’s try to understand better with doing some examples. First, I am creating service classes.

Then I will create a service provider, register services and get these services with different lifestyle.

I created service instances two times to see which one is recreating. And the result is;

Image for post
Image for post

As you can see, when I try to create services second time, only transient service is recreated but scoped and singleton aren’t created again. But in this example, it isn’t clear scoped service life time. In this example, both first instance and second instance are in the same scope. Let’s do another example to understand better for scoped service instances. I am modify the demo like following;

And result:

Image for post
Image for post

As you can see, scoped service instance is created more than one times in different scopes.

In this part, we tried to understand ASP.NET Core DI service provider, service collection and service registering lifestyle/lifetime.

IServiceCollection and IServiceProvider

In this part, I will do more examples about IServiceCollection and IServiceProvider to understand better how DI mechanism of ASP.NET Core is working.

In this step, we will examine some of ASP.NET Core DI features with doing examples. Because, some of these features are more important to understand how this features are used in framework. Also, if we know this features, we can design our project with better design. Let’s start to examples.

Factory Method

First, I will create objects to test.

And I am registering the objects for DI.

In second registration, I used factory overload method for register service and result.

Image for post
Image for post

Instance Registration

You can create an object instance before registering it. Object for instance registration.

And demo:

First, I created a new object before registering it’s type in DI. Then I resolved the registered instance by using both service.Implementation and serviceProvider.GetInstance methods. And the result:

Image for post
Image for post

Generic Type Registration

I think, this is one of the best features. Suppose we have a generic repository. If we want to register this repository for all types for DI, We should register all types separately like Repo, Repo, etc… But now, ASP.NET Core DI support generic registration. And its easy to register and resolve.

Multiple Registration

ASP.NET Core DI supports multiple registration with different options. This feature gives us some flexibility. Let’s do example to understand better. I am defining objects to test this feature.

I will show different usage of multiple registration feature with example.

First demo of above code, I added IHasValue object twice with different types. And when I want to get service, It gives me the last registered service.

Second demo, if I use TryAdd- method, it is not registered if there is a registered service.

And last one, I can replace registered service with another. You can understand better when you see the result.

Image for post
Image for post

DI Options and Using Autofac and Castle Windsor

In this last part, I will explain DI options, how to use ASP.NET Core DI with autofac and castle windsor.


There is a pattern that uses custom options classes to represent a group of related settings. As usual, I will explain it with example. First, download Microsoft.Extensions.Options.dll from nuget.

I created a class to calculate tax that uses an option class to get information how to calculate tax. I injected this option as IOption generic type. And here is the usage;

IServiceCollection has an extension method that named Configure. With using this method, we can define/change option values at compile time. When I run the code, here is the result.

Image for post
Image for post

In this example, we can set and use options in DI with adding values hardcoded. Of course we can read option values from an file like json. Let’s do an example for this.


The configuration API provides a way of configuring that can be read at runtime from multiple resources. These resources can be file (.ini, .json, .xml, …), cmd arguments, environment variables, in-memory objects, etc…

First, you should download Microsoft.Extensions.Options.ConfigurationExtensions.dll and Microsoft.Extensions.Configuration.Json.dll and I will add an appsettings.json to my project.

And I am modifying the demo like following.

I added ConfigurationBuilder to read options from json file. In json file, data structure is matching with configuration.GetSection(“TaxOptions”). And result is:

Image for post
Image for post

Using Castle Windsor and Autofac

Using another DI container is very easy. Just we are adding the nuget package and create an instance of container.

Castle Windsor

First, I am adding Castle.Windsor.MsDependencyInjection from nuget. And usage;


For using autofac, you should add the Autofac.Extensions.DependencyInjection nuget package to your project. And usage;

As you can see, after adding nuget packages, you can use them just using their own service provider or service register.

If you investigate source code of the example project, you can understand better.

Source code: ASP.NET Core Dependency Injection Training

This article was originally published on Volosoft Blog.



Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store