6

I have a base Controller ApplicationController that needs to grab the URL Host and do some processing before the child controllers are fired. Since controller constructors are fired before RequestContext is initialized I have to override Initialize method to do my processing.

ApplicationController:

    Protected Overrides Sub Initialize(ByVal requestContext As System.Web.Routing.RequestContext)
        MyBase.Initialize(requestContext)

        Dim host as String
        host = Request.Url.Host.ToString
    End Sub

What is the logic behind having Controller Constructors fire before the Initialize method?

Also what are the rules to what should be placed in the Initialize Method.

Zach L
  • 1,277
  • 4
  • 18
  • 37

2 Answers2

11

Assuming that constructors are the first instance method ever to be fired in a .NET class, that shouldn't come as a surprise and is not really something MVC specific. It's more how the .NET framework works.

The MVC framework needs to first instantiate a controller and then initialize it => it calls the constructor first. And because performing lots of code that could potentially might throw exceptions, etc... is not always best to be put in a constructor => the presence of the Initialize method. As far as this method is concerned I must admit that I have written lots of ASP.NET MVC code and never had to use it. Action filters always seemed like a better alternative.

So to answer your question:

Also what are the rules to what should be placed in the Initialize Method.

I've never ever put any code and never ever need to override this method. I've always preferred using action filters because this way I am no longer in the obligation of deriving from a common base controller (not that this is a problem).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • "I've always preferred using action filters because this way I am no longer in the obligation of deriving from a common base controller" re this statement, here's a couple of resources I found useful: http://stackoverflow.com/a/6119341/206297 ; http://odetocode.com/Blogs/scott/archive/2010/06/28/action-filter-versus-controller-base-class.aspx – ngm Oct 24 '12 at 10:19
-1

Sometimes, maybe you would want your request to initialize your variables, so in this case you should use the Initialize method.

For example, if you want to initialize some variables in a different way when the request is local or not, etc.

Boeckm
  • 3,264
  • 4
  • 36
  • 41