public void ConfigureServices(IServiceCollection services)
{
//将服务生命期的范围限定为单个请求的生命期
services.AddTransient<IUserService, UserService>();
}
获取服务
private readonly IUserService _userService;
public HomeController(IUserService userService)
{
_userService = userService;
}
public IActionResult Index()
{
var info = _userService.GetInfo();
return View();
}
IServiceProvider获取
private readonly IServiceProvider _service;
public UserController(IServiceProvider service)
{
_service = service;
}
[HttpGet]
public ActionResult GetName()
{
var _userService = (IUserService)_service.GetService(typeof(IUserService));
return Ok(_userService.GetName());
}
statrup中获取服务
var provider = services.BuildServiceProvider();
var userserivce = provider.GetService<IUserService>();
//或
var userservice2 = provider.GetRequiredService<IUserService>();