Web Api Controller and Thread Pool Web Api Controller and Thread Pool multithreading multithreading

Web Api Controller and Thread Pool


(i) In the context of a web api controller, when this request is received, is the controller instantiated and assigned to the spawned thread? (ii) When there are multiple http requests to the same api controller, will there be as many instances of the controller per spawned thread?

When a request is received, a controller instance is created by ControllerFactory or DependencyResolver.

Basically, main thread creates an controller instance, and then the same instance is shared between multiple threads until the request is completed.

(iii) In a scenario where a resource that is not thread safe (dbContext) is declared at the class level and instantiated in a constructor and then used in the class methods. Will there be issues committing and managing transactions?

Yes, share member or static are not thread safe. However, local variables inside action methods are thread safe.


Answer to your questions by point:
(i). Yes
(ii). No. Normally controllers are singleton and not thread safe. You create multiple threads to handle multiple request but they cal same controller instance (or service)
(iii). Yes. Its your responsibility to look after data sanity checks or thread safety concerns. If you don't then you can face all sort of issues like dirty read, dirty ride, thread safety... all kind of thread safety issues.

You can treat controller as service so just delegate the incoming requests to new sub-services or controllers by creating new instance like creating a new task handler for each request BUT you still need to think about thread safety of shared resources like Database.