urig
urig

Reputation: 16841

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

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?

Upvotes: 41

Views: 21676

Answers (2)

rollsch
rollsch

Reputation: 2780

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.

Upvotes: 6

Rowan Freeman
Rowan Freeman

Reputation: 16358

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.

Upvotes: 49

Related Questions