How can we inject the service dependency into the controller C# Asp.net 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.

Example

public interface ILog{
   void info(string str);
}
class MyConsoleLogger : ILog{
   public void info(string str){
      Console.WriteLine(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.

raja
Published on 25-Sep-2020 10:39:10
Advertisements