Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Controller Constructors fired before the Initialize method

Tags:

asp.net-mvc

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.

like image 651
zach attack Avatar asked May 18 '11 19:05

zach attack


1 Answers

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).

like image 194
Darin Dimitrov Avatar answered Nov 15 '22 08:11

Darin Dimitrov