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

简单来说就是

  • 有效地设计服务及其依赖关系。
  • 防止多线程问题。
  • 防止内存泄漏。
  • 防止潜在的错误。
相关推荐
小王不爱笑1326 小时前
Spring AOP(AOP+JDBC 模板 + 转账案例)
java·后端·spring
Python私教7 小时前
Rust基本语法
后端
Python私教7 小时前
Rust环境搭建
后端
jakeswang7 小时前
ServletLess架构简介
java·后端·servletless
夕颜1118 小时前
如何让 AI 按照你的预期输出
后端
q***56388 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
q***57509 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
猪猪拆迁队9 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构
GISer_Jing10 小时前
Node.js 开发实战:从入门到精通
javascript·后端·node.js
q***518911 小时前
Spring Boot 条件注解:@ConditionalOnProperty 完全解析
java·spring boot·后端