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

相关推荐
萧鼎7 分钟前
深入解析 Python 的 Word 模板引擎:docxtpl 全面指南
开发语言·python·word
Chan168 分钟前
场景题:如何设计一个分布式ID
java·开发语言·spring boot·java-ee·intellij-idea
chamu9914 分钟前
C++ 的可调用对象
开发语言·c++
tianyuanwo14 分钟前
Bash与Sh的诞生背景、底层原理及Linux多Shell解释器兼容性解析
linux·开发语言·bash
怦怦蓝24 分钟前
IDEA 项目打印日志全攻略:从基础使用到高级配置
java·开发语言·debug
meichaoWen26 分钟前
【nodejs】nodejs的一些基础知识
开发语言·前端·javascript
CoderCodingNo29 分钟前
【GESP】C++六级考试大纲知识点梳理, (1) 树的概念与遍历
开发语言·c++
A星空12330 分钟前
3519Hisidv500的QT配置
开发语言·qt
阿里嘎多学长32 分钟前
2026-01-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管