1

I know the lifetime of the controller class is transient by default, but I think it's better to be singleton. should explain to me why creators choose transient instead of singleton or scope lifetime?
Thanks a lot

2
  • Why do you think singleton is better?
    – devnull
    May 11, 2021 at 8:26
  • because I thought the controller has not any state!
    – Mujan
    May 11, 2021 at 8:54

1 Answer 1

9

There's a number of advantages to transient controllers. I cannot tell you whether any of them were the reason they were done that way - speculating about the intent of designers does not make a good SE question.

(As a side note, controllers aren't exactly transient, because by default they're not created by the DI container at all.)

One, this allows the controllers to have the HTTP context (including request and response) injected as members, easily accessible everywhere. Otherwise, they would need to be passed as arguments to the methods, polluting every single method with additional arguments.

Two, it's the most flexible. Singleton objects cannot properly depend on scoped or transient objects. Which means that you cannot depend on, say, an EF.Core DbContext (or anything that transitively depends on it), since DbContext implements the unit of work pattern. You'd have to inject every single such dependency as a [FromServices] argument to the controller methods, again polluting the argument lists.

Three, it immediately avoids any and all synchronization issues coming from concurrent access to controller member variables.

However, if you do want your controllers to be singletons, there's an SO answer describing how to do it here: https://stackoverflow.com/questions/62790945/how-to-make-controllers-scoped-or-singleton-instead-of-transient-in-asp-net-core

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.