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

In this article we will go through with one of the key features of .Net Core, Custom Service dependency injection in .Net core 1.1, particularly at controller’s action level .Here are some important points which will help you to understand the facts easily in the following excerpts:
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 of another object. A dependency is an object that can be used as service, which is a part of this article.
Earlier in .Net there were some well-known dependency resolvers like Unity, Autofac and Ninject and so on.
- .Net Core allows you to inject dependency out-of-the-box, there is no need to add the reference of the above mentioned dependency resolver. As soon as you create a solution you will be able to configure services easily, .Net Core manages this operation at its level that indeed helps a developer to get rid of this matter.
- This article explains about how to configure custom service in .Net core and inject that service object in controller’s constructor as well as in action method. In the earlier versions of .Net it used to not inject the dependency at Action level. This is recently introduced with the release of .Net core. Action level injection of service makes an application lighter than controller level. Consider a scenario when you have a number of action methods defined in a single controller and you have injected the service at controller’s constructor. Though it’s being used at one action only, it looks like it’s not worth it.
- Visual Studio 2017 Enterprise/Professional
- .Net Core 1.1
IMPLEMENTATION
In order to understand the dependency injection in .Net core 1.1, kindly refer to the given below image which states how the client application needs an object to access the implementation of given methods.

Now create a custom service class file as depicted below in screen shot:

FirstService class file has the following code snippet.
- using Microsoft.Extensions.Configuration;
- 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;
- }
- }
- }








Divya MohsnPosted Jul 22, 2018, 1:32 AM
Interesting Article Sir!