Home  >  Article  >  Backend Development  >  How can we inject service dependency into controller C# Asp.net Core?

How can we inject service dependency into controller C# Asp.net Core?

WBOY
WBOYforward
2023-09-10 12:49:021176browse

我们如何将服务依赖注入到控制器C# Asp.net Core中?

ASP.NET Core injects objects of dependent classes through constructors or methods By using the built-in IoC container.

Built-in containers are represented by IServiceProvider implementations Constructor injection is supported by default. Types (classes) managed by built-in IoC Containers are called services.

In order for the IoC container to automatically inject our application services, we first They need to be registered to the 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 the IoC container, In the ConfigureServices method of the Startup class. Configure service methods Contains a parameter of type IServiceCollection for registering the application services

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

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

The Add() method of the IServiceCollection instance is used to register services with IoC Container

We have specified ILog as the service type and MyConsoleLogger as its instance This will register the ILog service as a singleton Now, the IoC container will create a singleton object of MyConsoleLogger class and Whether we include the ILog as a constructor in the class's constructor or inject it into the class's constructor, Method parameters for the entire application.

The above is the detailed content of How can we inject service dependency into controller C# Asp.net Core?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How do arrays work in C#?Next article:How do arrays work in C#?