views:

15

answers:

1

Hi. Could you tell me MVC 2 Life cycle

The problem:

I got my own BaseController class where i try to get ControllerContext in constructor. It's "null"

Question: where does ControllerContext fill?

+2  A: 

The ControllerContext property is not assigned to in any of the base constructors in your inheritance hierachy. A controller is created by a controller factory and passed back without the ControllerContext property being assigned to.

Using Reflector, we can look at where the assignment takes place:

protected virtual void Initialize(RequestContext requestContext)
{
    this.ControllerContext = new ControllerContext(requestContext, this);
}

The Initialize method is invoked from the virtual Execute method call:

protected virtual void Execute(RequestContext requestContext)
{
    if (requestContext == null)
    {
        throw new ArgumentNullException("requestContext");
    }
    this.VerifyExecuteCalledOnce();
    this.Initialize(requestContext);
    this.ExecuteCore();
}

This means the earliest point at which you can access the ControllerContext property is by overriding the Execute or Initialize method (but calling base.Execute or base.Initialize first):

protected override void Execute(RequestContext requestContext)
{
  base.Execute(requestContext);

  // .ControllerContext is available from this point forward.
}

protected override void Initialize(RequestContext requestContext)
{
  base.Initialize(requestContext);

  // .ControllerContext is available from this point forward.
}

The latter (Initialize) is the absolute earliest point at which you can use the ControllerContext property, unless you handled the assignment yourself, which is not recommended (as parts of the framework will be dependent on having that property assigned to at that time).

Hope that helps.

Matthew Abbott
Thanks. That's what i need.
Brian J. Hakim