ASP.MVC 6 Features - Dependency Injection Modes

In the earlier post, I have shown how to make use of the built in Dependency Injection container in MVC 6. If you missed that you can go through it here. In that post I have explained about the Instance scope and here we will see the remaining modes.

To recap the AddInstance method will always return a new instance 

 services.AddInstance(new SampleRepository());

Transient is another one for specifying the scope of our instance during the object creation by DI container. By specifying it, we are instructing the container for creating a new instance whenever there is a request. The main difference between Instance and Transient methods is that in former it's our responsibility to create the instance where as it's upto the container in the latter

  services.AddTransient<ISampleRepository,SampleRepository>();

Here there is a slight change in syntax, instead of using the new operator we are creating a mapping which tells that whenever there is request for ISampleRepository,  create an instance of the SampleRepository class which is done by the contianer. So if we make the change in the example from the previous post and run it, the output will be

 

This time you will notice that the HashCodes for the two messages are different, because the GetMessage is being called from two differenent instances, because I am using two different repository objects in the controller.

Let's go back to startup.cs and change Transient scope to Singleton

services.AddSingleton<ISampleRepository,SampleRepository>();

Singleton method make sure that only one instance exists throughout the lifetime of the application. Meaning for all the requests for the ISampleRepository object the instance will be shared.

The last one is the Scoped method, which returns same instance for the lifetime of a single web request. That means if we call instance of ISampleRepository twice in a web request, it will return the same instance created. But when a new another request comes in, a new instance of the ISampleRepository will be created. Scoped services are really useful when you need to maintain state during a web request and are isolated from other requests happening at the same time.

The output will show the number for both the messages since we calling it in the same request

The two posts on DI injection is based on the idea from ASP.NET 5 MVC6 Dependency Injection in 6 Steps by .NET Liberty. But the code and images shown in post is from the author only


No Comments

Add a Comment