Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net Web API: Why are controllers created per request?

Tags:

asp.net-mvc

Mike Wasson's article "Dependency Injection for Web API Controllers" on www.asp.net says:

Dependenecy Scope and Controller Lifetime

Controllers are created per request...

Am I correct in understanding that ASP.NET Web API creates a new controller instance (and satisfies its dependencies) for each incoming request?

Is this approach not wasteful in that it creates and destroys many instances of the controller when in theory a single instance could be used for all requests?

like image 215
urig Avatar asked Aug 07 '14 06:08

urig


2 Answers

A controller contains information (state) about the incoming request.

If you had only one controller to handle many requests then they would all be confused and users would likely get some strange results.

like image 81
Rowan Freeman Avatar answered Sep 29 '22 14:09

Rowan Freeman


If it wasn't recreated each request you'd effectively have a singleton or static class meaning you'd need to handle resetting the classes state on exceptions and all sorts of other cases. The result would almost certainly mean bugs.

The overhead for creating a new context each time is a small price to pay for better code maintainability.

like image 25
rollsch Avatar answered Sep 29 '22 12:09

rollsch