穿越yin线的做网站,企业网站方案设计,wordpress 4.8 中文版,谷歌浏览器网页版进入ASP.NET Core 依赖注入#xff08;DI#xff09;容器支持三种服务的生命周期选项#xff0c;它们定义了服务实例的创建和销毁的时机。理解这三种生命周期对于设计健壯且高效的应用程序非常重要#xff1a; 瞬时#xff08;Transient#xff09;#xff1a; 瞬时服务每次…ASP.NET Core 依赖注入DI容器支持三种服务的生命周期选项它们定义了服务实例的创建和销毁的时机。理解这三种生命周期对于设计健壯且高效的应用程序非常重要 瞬时Transient 瞬时服务每次请求时都创建一个新的实例。这意味着如果在一个请求中两次解析服务你将得到两个不同的实例。用途适用于轻量级、无状态的服务。 作用域Scoped 作用域服务在每次请求时创建一次。同一个请求内多次解析服务将得到同一个实例不同的请求将会得到不同的实例。用途适用于需要在一个请求内共享数据或状态的服务如数据库上下文。 单例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(){MyPropertyGuid.NewGuid();}
}
public class Test2: ITest2
{public Guid MyProperty { get; set; }public Test1(){MyPropertyGuid.NewGuid();}
}
public class Test3: ITest3
{public Guid MyProperty { get; set; }public Test1(){MyPropertyGuid.NewGuid();}
}program注入服务
builder.Services.AddTransientITest1,Test1();
builder.Services.AddScopedITest2,Test2();
builder.Services.AddSingletonITest3,Test3();HomeController //这里采用了Action注入的方法 public IActionResult Index([FromServices] ITest2 test2,[FromServices] ITest1 test1){//transientViewBag.guid1 _test1.MyProperty;ViewBag.guid2 test1.MyProperty;//scopedViewBag.guid3 _test2.MyProperty;ViewBag.guid4 test2.MyProperty;//singletonViewBag.guid5 _test3.MyProperty;ViewBag.guid6 _test3.MyProperty;return View();}这里说明一下,我们采用了Action注入的方法,新注入了一个ITest2 ,来保证2个ITest2 在同一个作用域. index页面
{ViewData[Title] Home Page;
}div classtext-centerh1 classdisplay-4Welcome/h1pLearn about a hrefhttps://learn.microsoft.com/aspnet/corebuilding Web apps with ASP.NET Core/a./ph1transient(瞬时的):ViewBag.guid1/h1h1transient(瞬时的):ViewBag.guid2/h1h1scoped(范围的):ViewBag.guid3/h1h1scoped(范围的):ViewBag.guid4/h1h1singleton(单例的):ViewBag.guid5/h1h1singleton(单例的):ViewBag.guid6/h1
/div运行 瞬时的结果不一样 作用域的结果相同 页面刷新一下单例的始终保持一样瞬时的和作用域发生了改变。