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 依赖注入最佳实践

简单来说就是

  • 有效地设计服务及其依赖关系。
  • 防止多线程问题。
  • 防止内存泄漏。
  • 防止潜在的错误。
相关推荐
野犬寒鸦5 小时前
从零起步学习并发编程 || 第一章:初步认识进程与线程
java·服务器·后端·学习
我爱娃哈哈6 小时前
SpringBoot + Flowable + 自定义节点:可视化工作流引擎,支持请假、报销、审批全场景
java·spring boot·后端
李梨同学丶8 小时前
0201好虫子周刊
后端
思想在飞肢体在追8 小时前
Springboot项目配置Nacos
java·spring boot·后端·nacos
Loo国昌10 小时前
【垂类模型数据工程】第四阶段:高性能 Embedding 实战:从双编码器架构到 InfoNCE 损失函数详解
人工智能·后端·深度学习·自然语言处理·架构·transformer·embedding
ONE_PUNCH_Ge11 小时前
Go 语言泛型
开发语言·后端·golang
良许Linux11 小时前
DSP的选型和应用
后端·stm32·单片机·程序员·嵌入式
不光头强11 小时前
spring boot项目欢迎页设置方式
java·spring boot·后端
怪兽毕设12 小时前
基于SpringBoot的选课调查系统
java·vue.js·spring boot·后端·node.js·选课调查系统
学IT的周星星12 小时前
Spring Boot Web 开发实战:第二天,从零搭个“会卖萌”的小项目
spring boot·后端·tomcat