.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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值