ASP.NET Core 中 IoC 服务容器上下文中的请求是什么?

What are the requests in the context of an IoC services container in ASP.NET Core?

ASP.NET Core 中 IoC 服务容器上下文中的请求是什么?

我正在 these 教程的帮助下学习 ASP.NET 核心。我看到了以下摘录:

Scoped: IoC container will create an instance of the specified service type once per request and will be shared in a single request.

我不明白我们在这里谈论的是什么要求?这是否意味着每次后端控制器处理请求时,都会创建 IoC 容器提供的服务的新实例,并将其隐式放置在 class`s(代表控制器)字段中?还是其他类型的请求?

换句话说,如果我们有:

public void ConfigureServices(IServiceCollection services)
{
    services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped));
}

public class HomeController : Controller
{
    ILog _log;

    public HomeController(ILog log)
    {
        _log = log;
    }
    public IActionResult Index()
    {
        _log.info("Executing /home/index");

        return View();
    }
}

每次请求由 HomeController 控制器处理时,_log 中的 ILog 是否会有不同的实例?

是的,将为每个 HTTP 请求创建一个新对象。这对于非线程安全的有状态依赖项很有用。 Entity Framework 臭名昭著地要求以这种方式处理对象上下文。

如果依赖项是无状态的或线程安全的,您可以为它配置另一个生命周期,以便在应用程序的生命周期内只创建和重用一个对象。

像上面这样的控制器 HomeController 始终根据请求 创建。 IIRC,你不能改变它。