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

相关推荐
啦啦啦!几秒前
c++AI大模型接入SDK项目
开发语言·数据结构·c++·人工智能·算法
lcj25113 分钟前
【C语言】自定义类型1:结构体
c语言·开发语言·算法
jaysee-sjc6 分钟前
十七、Java 高级技术入门全解:JUnit、反射、注解、动态代理
java·开发语言·算法·junit·intellij-idea
Dxy123931021619 分钟前
Python使用SymSpell详解:打造极速拼写检查引擎
开发语言·python
时寒的笔记23 分钟前
js7逆向案例_禁止f12打开&sojson打开
开发语言·javascript·ecmascript
大鹏说大话27 分钟前
什么是“过早优化”?
开发语言
码云数智-园园28 分钟前
RESTful API vs GraphQL:设计哲学、性能博弈与选型指南
开发语言
每天吃饭的羊36 分钟前
nest,java对比
java·开发语言
sycmancia37 分钟前
Qt——登录对话框
开发语言·qt
专注VB编程开发20年37 分钟前
WebView2同时执行多个Promise异步任务性能损失1毫秒以内
开发语言