How can we inject the service dependency into the controller C# Core?

CsharpServer Side ProgrammingProgramming

ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container.

The built-in container is represented by IServiceProvider implementation that supports constructor injection by default. The types (classes) managed by built-in IoC container are called services.

In order to let the IoC container automatically inject our application services, we first need to register them with IoC container.


public interface ILog{
   void info(string str);
class MyConsoleLogger : ILog{
   public void info(string str){

ASP.NET Core allows us to register our application services with IoC container, in the ConfigureServices method of the Startup class. The ConfigureServices method includes a parameter of IServiceCollection type which is used to register application services

Register ILog with IoC container in ConfigureServices() method as shown below.

public class Startup{
   public void ConfigureServices(IServiceCollection services){
      services.AddSingleton<ILog, MyConsoleLogger>();

Add() method of IServiceCollection instance is used to register a service with an IoC container

We have specified ILog as service type and MyConsoleLogger as its instance This will register ILog service as a singleton Now, an IoC container will create a singleton object of MyConsoleLogger class and inject it in the constructor of classes wherever we include ILog as a constructor or method parameter throughout the application.

Published on 25-Sep-2020 14:09:10