0

Using ASP.NET MVC3.

What I'm trying to do is initialize a Controller field/property with an Application state variable.

I.e. in my Application_Start() method I have

Application["stats"] = new Stats(); //this is fine

Accessing this via a Controller method, e.g.

public ActionResult Index()
{
  return View(HttpContext.Application["stats"]); //this is also fine
}

works fine too.

//blows up with a 'Object reference not set to an object' error.
private Stats stats;
public HomeController()
{
    stats= (Stats)(HttpContext.Application["stats"]);
}

Anyone able to explain what I'm failing to understand + how to go about fixing the problem ? If there's a better way, let me know (and just in case you're wondering, I'm not trying to load up application configuration or anything; just to keep live stats on the state of the website)

Thanks in advance

-Marcin

2 Answers 2

1

The HttpContext is not yet initialize inside a controller constructor and is null.

If you need to access any HttpContext related stuff this could be done at most early inside the Initialize method:

public class HomeController: Controller
{
    private Stats stats;

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        stats = (Stats)(HttpContext.Application["stats"]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Genius ! Thanks heaps for that.
0

The HttpContext from your question is the property on the controller and as Darin said, that is not yet initialized. You can however use this:

private Stats stats;
public HomeController()
{
    stats= (Stats)(System.Web.HttpContext.Current.Application["stats"]);
}

4 Comments

What about unit testing? HttpContext.Current kinda kills all hopes :-)
Absolutely, unit testing will be a "challenge". Your solution is much better than mine. I just wanted to point out that you could get to the HttpContext in the constructor.
HttpContext.Current is something that you really don't want to use. No matter the circumstances. There are always better ways.
Thanks for that. Just trying to understand how unit testing would be easier using plain HttpContext rather than System.Web.HttpContext ? I found hanselman.com/blog/… which suggests that it's possible to mock it. So would the ability to mock be the only reason ? (Sorry, I've seen a few examples about mocking with Moq but haven't had a serious play with it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.