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

简单来说就是

  • 有效地设计服务及其依赖关系。
  • 防止多线程问题。
  • 防止内存泄漏。
  • 防止潜在的错误。
相关推荐
2601_962073812 小时前
Spring全面详解(基础版)
java·后端·spring
IT_陈寒2 小时前
Vite打包时的静态资源坑,我帮你踩过了
前端·人工智能·后端
考虑考虑2 小时前
kubectl命令
运维·后端·自动化运维
第五页的你3 小时前
ElasticSearch结合本地消息表实现搜索功能
后端
谢亮_vipxieliang3 小时前
ValidX分组验证详解:不同场景使用不同验证规则
java·spring boot·后端·spring cloud·eclipse·hibernate
超兔一体云3 小时前
MySQL索引优化实战——从慢查询到索引调优
后端·mysql
. . . . .4 小时前
服务端监控
后端
凤山老林4 小时前
Spring Boot 集成 Spring Vault:集中式密钥管理与动态凭证轮换
spring boot·后端·spring·vault·集中式秘钥管理
雨夜之寂4 小时前
雨夜-现在有办法识别是不是ai文章么
后端·面试
2601_962071174 小时前
八. Spring Boot2 整合连接 Redis(超详细剖析)
spring boot·redis·后端