当前位置: 首页 > news >正文

.netcore 6 ioc注入的三种方式

1、定义接口

public interface MyInterceptorInterface

2、实现接口

public class MyInterceptorImpl : MyInterceptorInterface

在构造中增加以下代码,便于观察

static ConcurrentDictionary<string, string> keyValues = new ConcurrentDictionary<string, string>();

public MyInterceptorImpl() {
    keyValues.TryAdd(Guid.NewGuid().ToString(), "12");
}

3、进行ioc注入

builder.Services.AddTransient<MyInterceptorInterface, MyInterceptorImpl>();

4、接收对应的注入对象

MyInterceptorInterface myInterceptorInterface;
MyAddScoped myAddScoped;

public ValuesController(MyInterceptorInterface myInterceptor, MyAddScoped myAddScoped)
{
    myInterceptorInterface = myInterceptor;
    this.myAddScoped = myAddScoped;
}

ps:使用[FromServices] 注解,这样也可以在方法中直接获取到,前提是已经注入

public string TestRoute([FromServices] MyInterceptorInterface myInterceptor)

5、调用对应接口

public string TestMyInterceptorAspect([FromBody] test str)
{
    //MyInterceptorInterface? myInterceptor = HttpContext.RequestServices.GetService<MyInterceptorImpl>();
    this.myAddScoped.Test();
    return this.myInterceptorInterface?.Test(str.str) ?? "error";
}

6、结论

1、注入有父类接收参数必须是父类,没有写父类只写子类可以用子类接收

三种方式
    Scoped方式:
        1、每一次web请求都会创建一个范围内存在的对象
    builder.Services.AddScoped<MyInterceptorInterface, MyInterceptorImpl>();

    AddSingletond方式:
        1、对象只创建一次,单例模式
    builder.Services.AddSingleton<MyInterceptorInterface, MyInterceptorImpl>();

    AddTransient方式:
        1、每次请求都创建、生命周期最短
    builder.Services.AddTransient<MyInterceptorInterface, MyInterceptorImpl>();

http://www.lryc.cn/news/277058.html

相关文章:

  • Python轴承故障诊断 (十)基于VMD+CNN-Transfromer的故障分类
  • 【复习】人工智能 第7章 专家系统与机器学习
  • 使用 Apache PDFBox 操作PDF文件
  • 【Python 常用脚本及命令系列 3.2 -- 检测到弹框跳出然后关掉它--脚本实现】
  • junit单元测试:使用@ParameterizedTest 和 @CsvSource注解简化单元测试方法
  • C# winform判断自身程序是否已运行,如果已运行则激活窗体
  • 超维空间M1无人机使用说明书——21、基于opencv的人脸识别
  • Redis 持久化——AOF
  • 华为云服务介绍(二)
  • mysql列题
  • cpu缓存一致性
  • Android Framework 常见解决方案(25-1)定制CPUSET解决方案-framework部分修改
  • PyTorch 参数化深度解析:自定义、管理和优化模型参数
  • 自承载 Self-Host ASP.NET Web API 1 (C#)
  • Vue2-子传父和父传子的基本用法
  • 使用numpy处理图片——镜像翻转和旋转
  • HTML5 article标签,<time>...</time>标签和pubdate属性的运用
  • Amazing OpenAI API:把非 OpenAI 模型都按 OpenAI API 调用
  • RK3568平台开发系列讲解(驱动篇)pinctrl 函数操作集结构体讲解
  • vue购物车案例,v-model 之 lazy、number、trim,与后端交互
  • 云原生Kubernetes: Kubeadm部署K8S 1.29版本 单Master架构
  • C++协程操作
  • 计算机配件杂谈-鼠标
  • 用Python来制作一个微信聊天机器人
  • 2024年第九届机器学习技术国际会议(ICMLT 2024) 即将召开
  • 算法训练day9Leetcode232用栈实现队列225用队列实现栈
  • linux驱动(四):platform
  • Guava:Cache强大的本地缓存框架
  • #{}和${}的区别?
  • string的模拟实现