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

相关推荐
源代码•宸4 小时前
分布式缓存-GO(分布式算法之一致性哈希、缓存对外服务化)
开发语言·经验分享·分布式·后端·算法·缓存·golang
云和数据.ChenGuang5 小时前
PHP-FPM返回的File not found.”的本质
开发语言·php·运维工程师·运维技术
R.lin5 小时前
Java 8日期时间API完全指南
java·开发语言·python
yangpipi-5 小时前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++
火钳游侠5 小时前
java单行注释,多行注释,文档注释
java·开发语言
有趣的我6 小时前
C++ 多态介绍
开发语言·c++
fie88896 小时前
波束赋形MATLAB代码实现
开发语言·matlab
丘狸尾6 小时前
gradio uv无法add
开发语言·python
sali-tec6 小时前
C# 基于halcon的视觉工作流-章67 深度学习-分类
开发语言·图像处理·人工智能·深度学习·算法·计算机视觉·分类
全栈陈序员7 小时前
【Python】基础语法入门(十七)——文件操作与数据持久化:安全读写本地数据
开发语言·人工智能·python·学习