.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 小时前
C语言_数据结构总结8:链式队列
c语言·开发语言·数据结构·链表·visualstudio·visual studio
千里码aicood1 小时前
[含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
开发语言·前端·python
讨厌下雨的天空1 小时前
C++之list
开发语言·c++·list
大麦大麦2 小时前
深入剖析 Sass:从基础到进阶的 CSS 预处理器应用指南
开发语言·前端·css·面试·rust·uni-app·sass
hhw1991122 小时前
c#面试题整理6
java·开发语言·c#
蠟筆小新工程師2 小时前
Deepseek可以通过多种方式帮助CAD加速工作
开发语言·python·seepdeek
天道有情战天下4 小时前
python flask
开发语言·python·flask
帅弟1505 小时前
Day4 C语言与画面显示练习
c语言·开发语言
qhs15735 小时前
Kotlin字符串操作在Android开发中的应用示例
android·开发语言·kotlin
Stack Overflow?Tan905 小时前
c++实现在同一台主机两个程序实现实时通信
开发语言·c++