asp.net core 依赖注入后的服务生命周期

发布于:2024-04-19 ⋅ 阅读:(20) ⋅ 点赞:(0)

ASP.NET Core 依赖注入(DI)容器支持三种服务的生命周期选项,它们定义了服务实例的创建和销毁的时机。理解这三种生命周期对于设计健壯且高效的应用程序非常重要:

  1. 瞬时(Transient)

    • 瞬时服务每次请求时都创建一个新的实例。这意味着如果在一个请求中两次解析服务,你将得到两个不同的实例。
    • 用途:适用于轻量级、无状态的服务。
  2. 作用域(Scoped)

    • 作用域服务在每次请求时创建一次。同一个请求内多次解析服务,将得到同一个实例;不同的请求将会得到不同的实例。
    • 用途:适用于需要在一个请求内共享数据或状态的服务,如数据库上下文。
  3. 单例(Singleton)

    • 单例服务在首次请求时创建(或者在你将服务注册到容器时,如果你选择了这样做),并且在应用程序的整个生命周期内保持同一个实例。所有后续的请求都将使用同一个实例。
    • 用途:适用于跨多个请求共享单一实例或状态的服务,如配置服务。

代码验证(这边创建一个asp.net core mvc)项目
Iservice

public interface ITest1
{
    public Guid MyProperty { get; set; }
}
public interface ITest2
{
    public Guid MyProperty { get; set; }
}
public interface ITest3
{
    public Guid MyProperty { get; set; }
}

service

public class Test1: ITest1
{
    public Guid MyProperty { get; set; }
   
    public Test1()
    {
        MyProperty=Guid.NewGuid();
    }
}
public class Test2: ITest2
{
    public Guid MyProperty { get; set; }
   
    public Test1()
    {
        MyProperty=Guid.NewGuid();
    }
}
public class Test3: ITest3
{
    public Guid MyProperty { get; set; }
   
    public Test1()
    {
        MyProperty=Guid.NewGuid();
    }
}

program注入服务

builder.Services.AddTransient<ITest1,Test1>();
builder.Services.AddScoped<ITest2,Test2>();
builder.Services.AddSingleton<ITest3,Test3>();

HomeController
//这里采用了Action注入的方法

 public IActionResult Index([FromServices] ITest2 test2,[FromServices] ITest1 test1)
    {
        //transient
        ViewBag.guid1 = _test1.MyProperty;
        ViewBag.guid2 = test1.MyProperty;
        //scoped
        ViewBag.guid3 = _test2.MyProperty;
        ViewBag.guid4 = test2.MyProperty;
        //singleton
        ViewBag.guid5 = _test3.MyProperty;
        ViewBag.guid6 = _test3.MyProperty;
        return View();
    }

这里说明一下,我们采用了Action注入的方法,新注入了一个ITest2 ,来保证2个ITest2 在同一个作用域.
index页面

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <h1>transient(瞬时的):@ViewBag.guid1</h1>
    <h1>transient(瞬时的):@ViewBag.guid2</h1>
    <h1>scoped(范围的):@ViewBag.guid3</h1>
    <h1>scoped(范围的):@ViewBag.guid4</h1>
    <h1>singleton(单例的):@ViewBag.guid5</h1>
    <h1>singleton(单例的):@ViewBag.guid6</h1>
</div>

运行
在这里插入图片描述
瞬时的结果不一样
作用域的结果相同
页面刷新一下单例的始终保持一样,瞬时的和作用域发生了改变。
在这里插入图片描述