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

相关推荐
知我Deja_Vu8 分钟前
详解 Lists.newArrayList() 的作用
java·开发语言
Andy Dennis15 分钟前
Java语法注意事项
java·开发语言·jvm
金刚狼8821 分钟前
qt和qt creator的下载安装
开发语言·qt
ShoreKiten23 分钟前
关于解决本地部署sqli-labs无法安装低版本php环境问题
开发语言·php
Hello World . .24 分钟前
Linux:线程间通信
linux·开发语言·vscode
liliangcsdn30 分钟前
深入探索TD3算法的推理过程
开发语言·php
谁刺我心32 分钟前
qt源码、qt在线安装器镜像下载
开发语言·qt
jllllyuz32 分钟前
实际气体状态方程:Peng-Robinson(P-R)方程计算指南
开发语言·matlab
LYS_061835 分钟前
C++学习(8)(文件输入输出,类和对象(1))
开发语言·c++·学习
历程里程碑36 分钟前
26信号处理一:从闹钟到进程控制的奥秘
linux·运维·服务器·开发语言·c++·算法·排序算法