MVC 控制器生命周期

我的理解是,控制器的构造函数不会在每个 Web 请求期间调用。假设这是真的,那么控制器的生命周期是什么?是在应用程序启动时“构建”的,然后缓存并调用每个 Web 请求注入到其中的 request 上下文吗?

需要说明的是,我并没有询问如何模拟构造函数的行为,而是使用 OnActionExecting 事件来启动通常在构造函数中执行的操作。此外,我在控制器上使用构造函数进行单元测试和系统测试。

谢谢!

38067 次浏览

If you use the default controller factory a new instance will be constructed for each request and that's the way it should be. Controllers shouldn't be shared among different requests. You could though write a custom factory that manages the lifetime of the controllers.

I'm afraid, your understanding is wrong. A controller (which should be a very thin and lightweight class and must not have any session-outliving state) is actually constructed on the fly for each and every web request. How else could a controller instance be specific to a certain view?

So there is no such thing as a "lifecycle" (other than that of the request)...

A controller is created for every request you do. Lets take an example.

   public class ExampleController : Controller{
public static userName;


public void Action1(){//do stuff}
public void Action2(){//do stuff}
public void AssignUserName(string username){
userName = username;


}
public string GetName(){ return userName;}




}

Now you can call the controller from the view passing a username. Don't hope to get the userName you set in the next request. it will return null. Thus for every request a new controller is created. You don't instantiate a controller anywhere in MVC like you instatiate an object from a class. Simply you don't have controller object memory pointer to call it as you do with other objects.

Go to this link. There is a good explanation on lifecycle of MVC controller.

ASP.Net MVC - Request Life Cycle