简体   繁体   English

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

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

What are the requests in the context of an IoC services container in ASP.NET Core? ASP.NET Core 中 IoC 服务容器上下文中的请求是什么?

I am learning the ASP.NET Core with the help of these tutorials.我正在这些教程的帮助下学习 ASP.NET Core。 And I come across the following excerpt:我遇到了以下摘录:

Scoped: IoC container will create an instance of the specified service type once per request and will be shared in a single request. Scoped:IoC 容器将为每个请求创建一次指定服务类型的实例,并将在单个请求中共享。

I can not grasp what request are we talking about here?我无法理解我们在这里谈论的是什么要求? Does it mean that every time a request is handled by a back end controller a new instance of the service provided by the IoC container will be created and implicitly placed in a class`s (which represents a controller) field?这是否意味着每次后端控制器处理请求时都会创建一个新的 IoC 容器提供的服务实例并将其隐式放置在类(代表控制器)字段中? Or does it mean other kinds of requests?或者这是否意味着其他类型的请求?

In other words if we have:换句话说,如果我们有:

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();
    }
}

will we have a different instance of the ILog in the _log every time a request is handled by the HomeController controller?每次请求由HomeController控制器处理时,我们会在_log有一个不同的ILog实例吗?

Yes, a new object will be created for each HTTP request.是的,将为每个 HTTP 请求创建一个新对象。 This can be useful for stateful dependencies that aren't thread-safe.这对于非线程安全的有状态依赖项非常有用。 Entity Framework object contexts are infamously required to be treated in this way.实体框架对象上下文需要以这种方式处理,这是臭名昭著的。

If the dependency is stateless, or thread-safe, you can configure it with another lifetime so that only a single object is created and reused for the lifetime of the application.如果依赖项是无状态的或线程安全的,您可以将其配置为另一个生命周期,以便在应用程序的生命周期内仅创建和重用单个对象。

Controllers like the above HomeController are always created per request .像上面的HomeController这样的控制器总是按请求创建。 IIRC, you can't change that. IIRC,你不能改变这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM