ASP.NET WebApi 极简依赖注入

文章目录

环境

  • .NET Core 7.0
  • ASP.NET Core
  • Visual Studio 2022

服务类

csharp 复制代码
public class T_TempService
{

    public T_TempService()
    {
    }


    public void Test()
    {
    }

}

启动项注入

csharp 复制代码
#region 依赖注入
builder.Services.AddTransient<T_TempService>();
#endregion

使用

csharp 复制代码
 public class ValuesController : ControllerBase
 {

     private readonly T_TempService tempService;
	///通过构造函数文件来获得依赖注入
     public ValuesController(T_TempService tempService)
     {
         this.tempService = tempService;
     }


     /// <summary>
     /// 获取数据
     /// </summary>
     /// <param name="model"></param>
     [HttpPost]
     public void Get()
     {

         tempService.Test();
     }
 }

依赖注入的优点

.Net Core WebApi Redis消息订阅
ASP.NET Core 依赖注入最佳实践

简单来说就是

  • 有效地设计服务及其依赖关系。
  • 防止多线程问题。
  • 防止内存泄漏。
  • 防止潜在的错误。
相关推荐
nbwenren12 小时前
Springboot中SLF4J详解
java·spring boot·后端
helx8212 小时前
SpringBoot中自定义Starter
java·spring boot·后端
rleS IONS13 小时前
SpringBoot获取bean的几种方式
java·spring boot·后端
lifewange13 小时前
Go语言-开源编程语言
开发语言·后端·golang
白毛大侠14 小时前
深入理解 Go:用户态和内核态
开发语言·后端·golang
王码码203514 小时前
Go语言中的数据库操作:从sqlx到ORM
后端·golang·go·接口
星辰_mya15 小时前
雪花算法和时区的关系
数据库·后端·面试·架构师
计算机学姐16 小时前
基于SpringBoot的兴趣家教平台系统
java·spring boot·后端·spring·信息可视化·tomcat·intellij-idea
總鑽風16 小时前
单点登录springcloud+mysql
后端·spring·spring cloud
0xDevNull16 小时前
Java 11 新特性概览与实战教程
java·开发语言·后端