.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++入门自学Day11-- String, Vector, List 复习
c语言·开发语言·数据结构·c++·容器
范范之交1 小时前
JavaScript基础语法two
开发语言·前端·javascript
Felven1 小时前
C. Game of Mathletes
c语言·开发语言
点云SLAM1 小时前
C++中内存池(Memory Pool)详解和完整示例
开发语言·c++·内存管理·内存池·new/delete·malloc/free
程高兴2 小时前
遗传算法求解冷链路径优化问题matlab代码
开发语言·人工智能·matlab
wow_DG2 小时前
【C++✨】多种 C++ 解法固定宽度右对齐输出(每个数占 8 列)
开发语言·c++·算法
CHEN5_022 小时前
【Java基础】反射,注解,异常,Java8新特性,object类-详细介绍
java·开发语言
Cx330❀3 小时前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
云间月13143 小时前
飞算JavaAI智慧文旅场景实践:从景区管理到游客服务的全链路系统搭建
java·开发语言
杜子不疼.3 小时前
《Python学习之使用标准库:从入门到实战》
开发语言·python·学习