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

相关推荐
KaMeidebaby7 分钟前
卡梅德生物技术快报|抗体筛选:抗体筛选中的噬菌体展示四参数调优——从流程设计到数据验证
开发语言·前端·javascript
大黄说说10 分钟前
接口频繁超时、报错?后端常见排查思路总结
开发语言·php
跨境小陈14 分钟前
2026 年如何使用 Python 抓取 Reddit 数据
开发语言·网络·python
code bean43 分钟前
【C#】 主构造函数(Primary Constructors)的来龙去脉
开发语言·c#
小柯南敲键盘1 小时前
AI批量翻译Temu商品标题的Python实践
开发语言·人工智能·python
逆境不可逃1 小时前
Java JUC 同步工具类一次讲透:CountDownLatch、CyclicBarrier、Semaphore、Phaser 与 AQS 共享模式
java·开发语言·python
大尚来也1 小时前
项目上线前必须检查的清单:避开线上重大事故
开发语言
q27551300421 小时前
AS717 Type-C转DP 8K方案外维少 AS717电路图
c语言·开发语言
CappuccinoRose2 小时前
Rust学习文档(二)
开发语言·后端·学习·rust
草莓熊Lotso2 小时前
【LangChain】核心组件详解:文档加载器(Document Loaders)
开发语言·c++·python·langchain·软件工程