Custom Service Dependency Injection in .Net Core 1.1

Introduction

There are various ways to inject a dependency in MVC. Dependency injection is a technique used to pass the required dependency so that the desired action is performed.

In this article, we will go through one of the key features of .Net Core as a custom service dependency injection in .Net Core 1.1, particularly at the controller’s action level.

Dependency Injection

Dependency Injection (DI) is a pattern that shows how we can create loosely coupled classes. It means Class A is not directly dependent on Class B and an object injects the dependency from another object. A dependency is an object that is used as a service.

Earlier in .Net, some common dependency resolvers used to exist like Unity, Autofac, Ninject, and so on.

.Net Core allows you to inject a dependency out-of-the-box, meaning that there is no need to add the reference of a dependency resolver. As soon as you create a solution, you will be able to configure services easily. .Net Core manages this operation automatically and helps the developer to get rid of manual tasks.

This article explains about how to configure custom service in .Net Core and inject that service object into the controller’s constructor and action methods. Earlier versions of .Net did not inject the dependency at the action level; this feature was recently introduced with the release of .Net core 1.1. The action level injection of service makes an application lighter than at the controller level. It is useful in a scenario where you have a number of action methods defined in a single controller, and you have injected the service at the controller’s constructor.

Prerequisites

  • Visual Studio 2017 Enterprise/Professional
  • .Net Core 1.1

Implementation

To understand the dependency injection in .Net core 1.1, please refer to the image below, which illustrates how the client application needs an object to access the implementation of the given methods.

Now create a custom service class file as depicted in the screenshot below:

The FirstService class file has the following code snippet:


namespace DotnetPiper.Services

{

    public interface IFirstService

    {

        string WelcomeEquinox();

    }

    public class FirstService : IFirstService

    {

        public string welcomeEquinoxStr { get; set; }

        public FirstService()

        {

            welcomeEquinoxStr = "Welcome Folks in .Net Core presentation!"; //Configuration["WelcomeEquinox"];

        }

        public string WelcomeEquinox()

        {

            return welcomeEquinoxStr;

        }

    }

}

Microsoft.Extensions.Configuration;

There is a startup class file which exists in the solution and has two methods: ConfigureServices and Configure. Refer to the image below to know more about startup class file location under solution structure.

This method executes its functionality at runtime. Both of the operations have a different set of objectives as shown below:

ConfigureServices: This method gets called by the runtime. Use this method to add services to the container. It takes one IServiceCollection object as an input. Refer to the screenshot given below.

Configure: This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

Register your custom services

To register your custom application services in ConfigureService method, put an interface definition object type that the container then requests. The second type represents the concrete type (class) that will be instantiated by the container.


services.AddSingleton<IFirstService, FirstService>();

 

If you notice in image above, it has an IServiceCollection object which registers IFirstService object as a singleton. However, there are two more ways to register your dependency in .Net core – AddScoped and AddTrsnsient. These are shown below:


services.AddScoped<ArticlesService>();

services.AddTransient<ArticlesService>();

 

Now, create a product controller under the Controllers folder and inject the dependency in either of the controller’s actions, as shown in the screenshot below:

Open Product Controller and inject IFirstService dependency in the Details action method. Refer to the code provided below for reference:


 public ActionResult Details([FromServices] IFirstService FirstService)

        {           

            _FirstService = FirstService;

            return Content(_FirstService.WelcomeEquinox());

        }

  

Note: The [FromServices] attribute is newly introduced in .Net Core and plays an important role in order to inject an abstract dependency at the action method level.

Let’s run the application and see how it works.

Press F5 and the application will open in a browser window to ensure that it is up and running.

Copy and paste the following URL to ensure the IFirstService availability at the action level.

http://localhost:64686/product/details

The outcome brings information through Custom service

And there you have it! You have successfully injected a dependency using .Net Core.

Sachin Kalia

Sachin Kalia

Sachin Kalia is a Technical Lead at 3Pillar Global, working out of our office in Noida, India. He is Microsoft MVP which is the most prominent recognition from Microsoft for helping the community for free in learning technologies. He has expertise in building and working with high-performance teams delivering enterprise product. Sachin is a passionate blogger and speaker and loves to dive deep into trending technologies. His interest areas are .Net, Asp.Net, WebAPi, Microservices, Cognitive Services, Artificial Intelligence and Azure(Cloud). He loves swimming and playing cricket and table tennis and love traveling with friends and family.

Leave a Reply

Related Posts

Take 3, Scene 23: The Influence and Evolution of Blockchain Michael Lisse and Derek Tiffany join us in the studio for this episode of Take 3 to talk about the influence and evolution of blockchain in the financ...
Take 3, Scene 24: The Influence and Evolution of Blockchain,... On this episode of Take 3, we're joined again by Michael Lisse and Derek Tiffany to hear their fresh insights from the Consensus Blockchain Summit in ...
Controlling Access by Using Impersonation Overview Impersonation is a security feature that enables an application to be executed with a pre-defined identity. Using trusted ASP.NET applicatio...
Automated Mobile App Testing in Amazon Device Farm Amazon Device Farm (ADF) is an app testing service that facilitates testing and interaction with Android, iOS, and Web apps on real, physical phones a...
How to Initialize a Postgres Docker with a Million-Plus Reco... Besides the official Docker documentation, there are several good sources on the internet where you can read about how to kick-start your Dockerized e...

SUBSCRIBE TODAY


Sign up today to receive our monthly product development tips newsletter.