服务类型 | 同一个 HTTP 请求的范围 | 多个不同 HTTP 请求 |
Singleton Service | 同一个实例 | 同一个实例 |
Scoped Service | 同一个实例 | 新实例 |
Transient Service | 新实例 | 新实例 |
自己理解的测试代码,简单的仓储模式
[Route("api/User")]
[ApiController]
public class UserController : ControllerBase
{
IUserService userService;
INewService newService;
ICompanyService companyService;
public UserController(
IUserService userService,
INewService newService,
ICompanyService companyService)
{
this.userService = userService;
this.newService = newService;
this.companyService = companyService;
}
/// <summary>
/// services.AddSingleton<IUserService, UserService>();
/// 单例模式,应用程序生命期内,永远一致:s1==s2
/// </summary>
/// <returns></returns>
[HttpGet("UserID")]
public IList<long> GetUserID()
{
var result = new List<long>();
var s1 = userService.GetHashCode();//获取此次请求时的注入对象hashcode
var s2 = HttpContext.RequestServices.GetService(typeof(IUserService)).GetHashCode();//再次获取此次请求时的注入对象hashcode
result.Add(s1);
result.Add(s2);
result.Add(userService.GetUserID());
return result;
}
/// <summary>
/// services.AddScoped<INewService, NewService>();
/// 同一个Http请求,注入的对象一致:s1==s2,
/// 不同的htpp请求注入对象不一致:s1!=s2
/// </summary>
/// <returns></returns>
[HttpGet("NewID")]
public IList<long> GetNewID()
{
var result = new List<long>();
var s1 = newService.GetHashCode();//获取此次请求时的注入对象hashcode
var s2 = HttpContext.RequestServices.GetService(typeof(INewService)).GetHashCode();//再次获取此次请求时的注入对象hashcode
result.Add(s1);
result.Add(s2);
return result;
}
/// <summary>
/// services.AddTransient<ICompanyService, CompanyService>();
/// 同一个Http请求,注入的对象不一致: s1!=s2,
/// 不同的htpp请求注入对象更加是不一致: s1!=s2
/// </summary>
/// <returns></returns>
[HttpGet("CompanyID")]
public IList<long> GetCompanyID()
{
var result = new List<long>();
var s1 = companyService.GetHashCode();//获取此次请求时的注入对象hashcode
var s2 = HttpContext.RequestServices.GetService(typeof(ICompanyService)).GetHashCode();//再次获取此次请求时的注入对象hashcode
result.Add(s1);
result.Add(s2);
return result;
}
}
startup.cs添加配置
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IUserRespository, UserRespository>();
services.AddScoped<INewRespository, NewRespository>();
services.AddTransient<ICompanyRespository, CompanyRespository>();
services.ConfigureInvalidModelState();
services.AddControllers();
}