zoukankan      html  css  js  c++  java
  • .NetCore【依赖注入:AddTransient、AddSingleton、AddScoped的区别 】

    service.AddTransient<ITranTest, TranTest>();
    
    service.AddSingleton<ISingTest, SingTest>();
    
    service.AddScoped<ISconTest, SconTest>();

    一、使用方式

    service.AddTransient<ITranTest, TranTest>();
    
               service.AddSingleton<ISingTest, SingTest>();
    
               service.AddScoped<ISconTest, SconTest>();

    二、生命周期

    权重:

    AddSingleton→AddTransient→AddScoped

    AddSingleton的生命周期:

    项目启动-项目关闭   相当于静态类  只会有一个  

    AddScoped的生命周期:

    请求开始-请求结束  在这次请求中获取的对象都是同一个 

    AddTransient的生命周期:

    请求获取-(GC回收-主动释放) 每一次获取的对象都不是同一个

    控制器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    [HttpGet]
           public IActionResult SetTest()
           {
               sing.Age = 18;
               sing.Name = "小红";
     
               tran.Age = 19;
               tran.Name = "小明";
     
               scon.Age = 20;
               scon.Name = "小蓝";
     
               aService.RedisTest();
     
               return Json("OK");
           }

      注入

    1
    2
    3
    4
    5
    6
    public static void AddTestTran(this IServiceCollection service) {
               service.AddTransient<ITranTest, TranTest>();
               service.AddSingleton<ISingTest, SingTest>();
               service.AddScoped<ISconTest, SconTest>();
               service.AddScoped<IAService, AService>();
           }

      服务:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class AService: IAService
        {
            private ISingTest sing; ITranTest tran; ISconTest scon;
            public AService(ISingTest sing, ITranTest tran, ISconTest scon)
            {
                this.sing = sing;
                this.tran = tran;
                this.scon = scon;
            }
            public void RedisTest()
            {
     
            }
        }

      

    AddSingleton的对象没有变

    AddScoped的对象没有变化

    AddTransient的对象发生变化

    ------------------------------------------------------------

    请求get

    AddSingleton的对象没有变

    AddScoped的对象发生变化

    AddTransient的对象发生变化

    注意:

    由于AddScoped对象是在请求的时候创建的

    所以不能在AddSingleton对象中使用

    甚至也不能在AddTransient对象中使用

    所以权重为

    AddSingleton→AddTransient→AddScoped

    不然则会抛如下异常

    
    

    原文地址:https://www.cnblogs.com/AnAng/p/9370913.html

  • 相关阅读:
    转:浅谈UNIX下Apache的MPM及httpd.conf配置文件中相关参数配置
    LINUX DNS解析的3种修改方法~
    Linux ftp访问控制配置,包括访问ftp权限和访问ftp目录权限
    composer 安装提示 PHP Warning: readfile(): SSL operation failed with code 1
    PHPExcel yii2 加载使用
    转:mysql根据经纬度查找排序
    bootstrap无限级分类 jq拓展 之前的无限级分类的封装版~
    ACM学习历程—HDU1717 小数化分数2(gcd)
    ACM学习历程—HDU1716 排列2(dfs && set容器)
    ACM学习历程—BestCoder 2015百度之星资格赛1001 大搬家(递推 && 组合数学)
  • 原文地址:https://www.cnblogs.com/qiupiaohujie/p/14406048.html
Copyright © 2011-2022 走看看