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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With