Asp.Net Core中服务的生命周期选项区别与用法详解(2)

[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IOperationService _operationService; public ValuesController(IOperationService operationService) { _operationService = operationService; } [HttpGet] [Route(nameof(GetGuidString))] public ActionResult<string> GetGuidString() { return string.Join("\n", _operationService.GetGuidString()); } }

在StartUp中完成服务注入逻辑,这里实现服务注入的方式多种均可。

services.AddTransient<IOperationTransient, OperationTransient>(); services.AddScoped<IOperationScoped, OperationScoped>(); services.AddSingleton<IOperationSingleton, OperationSingleton>();//应用程序启动时便注入该实例 services.AddSingleton<IOperationInstance>(new OperationInstance(Guid.Empty)); services.AddTransient<IOperationService, OperationService>();

通过访问预期Api地址可以得到不同的四种基础服务的Guid信息,

第一次启动程序(不关闭)发起访问:

Asp.Net Core中服务的生命周期选项区别与用法详解

  

第二次(第一次基础上再次访问)发起访问:

Asp.Net Core中服务的生命周期选项区别与用法详解

  

可以看见,两次访问下,Singleton和Instance是相同的,都是由应用程序启动时和应用服务加载时决定完毕,Singleton在首次进入服务时进行分配,并始终保持不变,而Instance在应用程序启动时,便将实例注入,进入服务也保持着最先的实例,没有重新分配实例。而Transient和Scoped则进行着变化。

关闭程序,重启,第三次发起访问:

Asp.Net Core中服务的生命周期选项区别与用法详解

  

可以见到,Singleton和Instance都发生了变化,也说明了之前在Singleton和Instance处写上的作用。

接下来开始设计Transient和Scoped的不同之处,对于已有代码加上新功能,此次我们只针对Scoped和Transient进行比较。

首先在StartUp中将HttpContextAccessor服务注入,目的是在后期能够针对Scoped获取新的服务实例(尽管两个实例是相同的)。

services.AddHttpContextAccessor();

接着在聚合服务中增加一个方法,用来针对Transient、Scoped测试。

/// <summary> /// 获取Transient、Scoped的Guid码 /// </summary> /// <returns></returns> List<string> GetTransientAndScopedGuidString();

在聚合服务实现中实现该方法并对已有的服务重新获取实例,得到不同实例下的Guid码。

public List<string> GetTransientAndScopedGuidString() { //var tempTransientService = (IOperationTransient)ServiceLocator.Instance.GetService(typeof(IOperationTransient)); var tempTransientService = (IOperationTransient)_httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IOperationTransient)); var tempScopedService = (IOperationScoped)_httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IOperationScoped)); return new List<string>() { $"原生Transient请求服务:"+_transientOperation.GetGuid(), $"手动Transient请求服务:"+ tempTransientService.GetGuid(), $"原生Scoped请求服务:"+_scopedOperation.GetGuid(), $"手动Scoped请求服务:"+tempScopedService.GetGuid(), }; }

在控制器部分调用该聚合服务即可,并返回相应的结果,本次我返回的结果:

Asp.Net Core中服务的生命周期选项区别与用法详解

  

可以看到,对于Scoped来讲,一次请求内多次访问同一个服务是共用一个服务实例的,而对于Transient则是,每次访问都是新的服务实例。

至此,对于这四种服务生命周期算是掌握的差不多了。 

参考:

蒋老师文章: https://www.jb51.net/article/150103.htm

田园里的蟋蟀:https://www.jb51.net/article/150102.htm

总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdsjxp.html