This article explains the dependency injection feature available out of the box in ASP.NET core (ASP.NET 5). It will also cover some of the basics of dependency injection so that everyone can get the most out this article.
What is dependency Injection
Dependency Injection is the process of “injecting” the “dependency” whenever the dependency is requested by a client, where the dependency may be another service which the client (requester) may have no means of knowing how to create.
As an analogy, imagine a person (client) going to office carrying his lunch cooked by himself. In this scenario, the person has a “dependency” on food. But he had to know how to cook his food. But honestly, not everyone (client) knows to cook, but people do need food (dependency). This is where restaurants play the role of dependency Injection. They can supply food (“inject dependency”) to the people (client) without the person (client) needing to know how to cook.
This is also called as Inversion of control. Since the control for creation of the service has been passed from the requester to another entity which takes care of creating the dependencies needed by a class to perform its tasks. The entity which takes care of creating these requested dependencies and injecting them automatically to the client is known as the DI (dependency Injection) container.
Dependency Injection in ASP.NET Core
Ok, enough said about what dependency injection is. I am sure most of you knew it. If not, this is a great feature to know and a great tool to add to your tool belt! Let us now look at how to implement dependency injection out of the box in ASP.NET core.
ASP.NET core applications can leverage built in framework support for implementing dependency injection. It has support for the following types of lifetimes for configured services (injected dependencies).
- Transient – A new instance of the service is created each time it is requested. It can be used for stateless and light weight services.
- Scoped – A single instance is created once per request.
- Singleton – Created only once the first time they are requested.
Now for some code!
Use case
Implement a UniqueKeyProvider service. For demonstrating the lifetimes, we will create three differently named interfaces (one for each type of lifetime) for UniqueKeyprovider, all inheriting from the same parent interface having a single property, UniqueKey.
Also, to further illustrate the scoped and singleton lifetime, we will create another service, SomeService, which will have a dependency on all the three different UniqueKeyProvider services (the three different lifetime services).
1. Service Interface definition
Please note the three differently named interfaces, one for demonstrating each type of lifetime.
- namespace DependencyInjectionASPNetCore.Services
- {
- public interface IUniqueKeyProvider
- {
- Guid UniqueKey
- {
- get;
- set;
- }
- }
- public interface ITransientUniqueKeyProvider: IUniqueKeyProvider
- {}
- public interface IScopedUniqueKeyProvider: IUniqueKeyProvider
- {}
- public interface ISingletonUniqueKeyProvider: IUniqueKeyProvider
- {}
- }
- namespace DependencyInjectionASPNetCore.Services
- {
- public class UniqueKeyProvider: ITransientUniqueKeyProvider,
- ISingletonUniqueKeyProvider,
- IScopedUniqueKeyProvider
- {
- public Guid UniqueKey
- {
- get;
- set;
- }
- public UniqueKeyProvider(Guid uniqueKey)
- {
- UniqueKey = uniqueKey;
- }
- }
- }
Now register your services in the startup.cs file. This is the step where you are actually configuring your dependency injection container. You are basically instructing your dependency injection container that if the user requests for the service, ITransientUniqueKeyProvider, then please provide with a transient scoped instance of UniqueKeyProviderclass and similarly for the other services.
You need to register your services in the ConfigureServices method in the startup.cs file. Please refer to the code below for registration,
- services.AddTransient<ITransientUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid()));
- services.AddScoped<IScopedUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid()));
- services.AddSingleton<ISingletonUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid()));
- services.AddTransient<ISomeService, SomeService>();
4. IsomeService and Someservice Implementation
- public class ISomeService
- {
- ITransientUniqueKeyProvider TransientUniquekeyProvider
- {
- get;
- set;
- }
- IScopedUniqueKeyProvider ScopedUniquekeyProvider
- {
- get;
- set;
- }
- ISingletonUniqueKeyProvider SingletonUniquekeyProvider
- {
- get;
- set;
- }
- }
- public class SomeService: ISomeService
- {
- public ITransientUniqueKeyProvider TransientUniquekeyProvider
- {
- get;
- set;
- }
- public IScopedUniqueKeyProvider ScopedUniquekeyProvider
- {
- get;
- set;
- }
- public ISingletonUniqueKeyProvider SingletonUniquekeyProvider
- {
- get;
- set;
- }
- public SomeService(ITransientUniqueKeyProvider transientprovider,
- IScopedUniqueKeyProvider scopedprovider,
- ISingletonUniqueKeyProvider singletonprovider)
- {
- TransientUniquekeyProvider = transientprovider;
- ScopedUniquekeyProvider = scopedprovider;
- SingletonUniquekeyProvider = singletonprovider;
- }
- }
5. Home Controller
- public class HomeController: Controller
- {
- private ITransientUniqueKeyProvider _transientUniquekeyProvider;
- private IScopedUniqueKeyProvider _scopedUniquekeyProvider;
- private ISingletonUniqueKeyProvider _singletonUniquekeyProvider;
- private ISomeService _someserviceProvider;
- public HomeController(ITransientUniqueKeyProvider transientprovider,
- IScopedUniqueKeyProvider scopedprovider,
- ISingletonUniqueKeyProvider singletonprovider, ISomeService someserviceprovider)
- {
- _transientUniquekeyProvider = transientprovider;
- _scopedUniquekeyProvider = scopedprovider;
- _singletonUniquekeyProvider = singletonprovider;
- _someserviceProvider = someserviceprovider;
- }
- public IActionResult Index()
- {
- ViewBag.transientID = _transientUniquekeyProvider.UniqueKey;
- ViewBag.scopedID = _scopedUniquekeyProvider.UniqueKey;
- ViewBag.singletonID = _singletonUniquekeyProvider.UniqueKey;
- ViewBag.someServiceProvider = _someserviceProvider;
- return View();
- }
- }
6. Index View
In the view file, we are just displaying the values that we set in the view bag. Results provided in the next section.
- <div style="margin-top:35px">
- lt;pstyle="font-weight:bold;text-decoration:underline">
- These are the values that were injected into the home controller
- </p>
- <p>
- Transient value of Guid: @ViewBag.transientID
- </p>
- <p>
- Scoped value of Guid: @ViewBag.scopedID
- </p>
- <p>
- Singleton value of Guid: @ViewBag.singletonID
- </p>
- </div>
- <div>
- <p style="font-weight:bold;text-decoration:underline">
- These are the values that were injected into Someservice Implementation
- </p>
- <p>
- Transient value of Guid: @ViewBag.someServiceProvider.TransientUniquekeyProvider.UniqueKey
- </p>
- <p>
- Scoped value of Guid: @ViewBag.someServiceProvider.ScopedUniquekeyProvider.UniqueKey
- </p>
- <p>
- Singleton value of Guid: @ViewBag.someServiceProvider.SingletonUniquekeyProvider.UniqueKey
- </p>
- </div>
Output in screen
Page load first time,

Page load second time,
I really hope it was useful and fun. Happy coding!

Neel BhattPosted Aug 22, 2016, 10:39 AM
Have a look here for more: https://neelbhatt40.wordpress.com/2016/08/22/dependency-injection-in-mvc-1-0asp-net-core/
kalu singh raoPosted Jun 15, 2016, 2:59 PM
Nice...
Nataraj Gandhi ArunachalamPosted May 20, 2016, 11:11 AM
Thank you all for your kind comments!
ali imranPosted May 20, 2016, 10:21 AM
Finally clear understanding about DI. Thanks a lot
Sonu ChaudharyPosted May 19, 2016, 11:34 AM
good share
Pradeep SahooPosted May 19, 2016, 10:08 AM
good share
Nataraj Gandhi ArunachalamPosted May 18, 2016, 9:39 PM
Thanks everyone!
Neeraj KumarPosted May 18, 2016, 1:00 PM
Nice one...
Prasanna MuraliPosted May 18, 2016, 10:40 AM
Nice one...
Debasis SahaPosted May 18, 2016, 10:19 AM
Good One..
Thiruppathi RPosted May 18, 2016, 10:17 AM
Good ..