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

相关推荐
kaoshi100app6 分钟前
2026年注册安全工程师报考条件解读
开发语言·人工智能·职场和发展·学习方法
是三好8 分钟前
java集合
java·开发语言
凯子坚持 c10 分钟前
Qt常用控件指南(5)
开发语言·数据库·qt
foundbug99911 分钟前
MATLAB实现轴承刚度计算
开发语言·matlab
C++ 老炮儿的技术栈12 分钟前
CMFCEditBrowseCtrl用法一例
c语言·开发语言·c++·windows·qt·visual studio code
Three~stone12 分钟前
Matlab R2024b 保姆级安装教程(附:解决win10问题)
开发语言·算法·matlab
ytttr87315 分钟前
基于MATLAB的一维对流扩散方程数值求解
开发语言·算法·matlab
程序员spped19 分钟前
分享一套非常不错的基于Python的Django图书馆(自习室)座位预约管理系统
开发语言·python·座位预约
QQ_18808380019 分钟前
基于Python和django的贫困地区儿童在线帮扶系统
开发语言·python·django
学海无涯书山有路26 分钟前
Android ViewBinding 新手详解(Java 版)—— 结合 ViewModel+LiveData 实战
android·java·开发语言