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

相关推荐
小王不爱笑13223 分钟前
IO 模型
开发语言·python
知我Deja_Vu42 分钟前
【避坑指南】ConcurrentHashMap 并发计数优化实战
java·开发语言·python
AI+程序员在路上1 小时前
CANopen 协议:介绍、调试命令与应用
linux·c语言·开发语言·网络
2401_831824961 小时前
基于C++的区块链实现
开发语言·c++·算法
m0_518019482 小时前
C++与机器学习框架
开发语言·c++·算法
ZTLJQ2 小时前
深入理解逻辑回归:从数学原理到实战应用
开发语言·python·机器学习
qq_417695052 小时前
C++中的代理模式高级应用
开发语言·c++·算法
波波0072 小时前
每日一题:.NET 中的“反射”是什么?
开发语言·.net
qq_461489333 小时前
C++与Qt图形开发
开发语言·c++·算法
Evand J3 小时前
【三维飞行器】RRT路径规划与TOA定位仿真系统,MATLAB例程,路径起终点、障碍物、TOA锚点等均可设置。附下载链接
开发语言·matlab·无人机·定位·rrt·toa·三维航迹规划