Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-09-10 12:49:02
forward
1267 people have browsed it

我们如何将服务依赖注入到控制器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);
   }
}
Copy after login

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>();
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template