When we use the IOC in MVC, how do you register the Controller life cycle (lifestyle)?
I've never thought about it before. As we all know in the MVC development process, most of the components are registered to the container in perwebrequest way, controller is no exception, in Castle, for example, the code of the registered controller is as follows:
public class Controllerinstaller:iwindsorinstaller {public void Install (IWindsorContainer container, Iconfigurationstore store) { container. Register ( classes.fromthisassembly (). Basedon<controller> (). Withservice.self (). Lifestyleperwebrequest ()); } }
After a long-term project run proves that this way does not bring any problems, such code runs very well.
Later in doing WEBAPI development, and perwebrequest the way to register the WEBAPI controller. Because of the project needs, we call the WEBAPI controller in the MVC controller in In-memory Way, the code will report the following exception: cannot reuse an ' HomeController ' instance. ' HomeController ' have to be constructed per incoming message. Check your custom ' ihttpcontrolleractivator ' and make sure that it'll not manufacture the same instance.
For specific explanations, see Controller in ASP. NET Web API
Obviously, Webapi wanted to create a new controller for each request, and our in-memory call in MVC was to request the same controller in the same WebRequest. We are aware of the problem with Webapi's lifestyle approach, and the problem is solved after the change to Lifestyletransient.
So what is the controller's lifestyle perwebrequest or transient? I found such an explanation in Stackoverfllow:
MVC controllers is transient. Thinking about it, this makes sense for a few reasons. First, if a single instance are used to service multiple requests and if multiple requests happen to hits the same Controlle R at the same time, you ' re going to experience some fairly bizarre race conditions. Second, HTTP is by its very nature stateless, and requests exist independently of one another. This was reflected in the transient lifestyle of controllers.
This means: Controller is transient, first of all, the 1th is to confirm the problems encountered in our project, second, HTTP is stateless, each request is independent of each other, this also coincides with the definition of transient.
In a comprehensive analysis, the controller in MVC or WEBAPI should be transient.
Is the controller's life cycle transient or perwebrequest?