qqqqqqq
qqqqqqq

Reputation: 2227

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?

I am learning the ASP.NET Core with the help of these tutorials. 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.

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? 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?

Upvotes: 1

Views: 197

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233307

Yes, a new object will be created for each HTTP request. 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. IIRC, you can't change that.

Upvotes: 2

Related Questions