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

相关推荐
tiana_6 小时前
写了个零依赖的 Go 版本管理器,curl | bash 完事
开发语言·golang·bash
嘘嘘出差6 小时前
Python 爬虫入门实战:爬取豆瓣电影 Top 250
开发语言·爬虫·python
爱写代码的倒霉蛋6 小时前
实现协程的三种方式
开发语言·python
CS创新实验室6 小时前
NumPy数组的C风格和Fortran风格
c语言·开发语言·numpy
逝水无殇7 小时前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
朱永博7 小时前
使用Onnruntime实现Padim/Patchcore推理
开发语言·c#
前端H7 小时前
Biome & Rolldown:Rust 工具链接管前端基建
开发语言·前端·rust
天天进步20157 小时前
UI-TARS 源码解析 #4:UI-TARS 与传统 RPA 的区别:为什么它不是简单的坐标点击脚本?
开发语言
运维行者_8 小时前
广域网性能监控:分布式IT架构下的链路质量保障
开发语言·网络·分布式·后端·架构·数据库架构
梅雅达编程笔记8 小时前
零基础学 Python 第7章 | 字典 dict:键值对存储
开发语言·python·beautifulsoup·numpy·pandas