.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>();

相关推荐

  1. .netcore 6 ioc注入方式

    2024-01-10 16:40:05       52 阅读
  2. 对于IOC注入方式注解和XML)

    2024-01-10 16:40:05       35 阅读
  3. ES6 export暴露和引用方式

    2024-01-10 16:40:05       46 阅读
  4. ES6暴露方法

    2024-01-10 16:40:05       84 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-10 16:40:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-10 16:40:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-10 16:40:05       82 阅读
  4. Python语言-面向对象

    2024-01-10 16:40:05       91 阅读

热门阅读

  1. MinIO (五) .net core实现分片上传

    2024-01-10 16:40:05       40 阅读
  2. Hadoop之mapreduce参数大全-2

    2024-01-10 16:40:05       43 阅读
  3. Spring Boot 中自定义中文校验注解的实现

    2024-01-10 16:40:05       64 阅读
  4. K8S---kubectl edit命令

    2024-01-10 16:40:05       55 阅读
  5. 【2023】ArrayList和LinkedList详解介绍对比

    2024-01-10 16:40:05       60 阅读
  6. for循环延时时间计算

    2024-01-10 16:40:05       53 阅读
  7. Gorm 入门介绍与基本使用

    2024-01-10 16:40:05       45 阅读
  8. 《Linux C编程实战》笔记:线程终止

    2024-01-10 16:40:05       47 阅读