views:

62

answers:

4

I have a number of Controllers, and I want them all to have an interface to a PageConfiguration object that needs to be created based on the URL. I'm not sure how to do this other than to create the interface in the action methods, because they have access to Request.QueryString, where the Controllers constructors don't. Do I need to create a global object in Application_BeginRequest? What approaches could I take to satisfy this requirement? Thanks

edit: this code outlines what I'm trying to do:

public class ResultsController : Controller
{
    private IPageConfiguration page;

    public ResultsController()
    {
        page = new PageConfiguration("?"); // needs value from query string
    }
}

public class FactsheetController : Controller
{
    private IPageConfiguration page;

    public FactsheetController()
    {
        page = new PageConfiguration("?"); // needs value from query string
    }
}
A: 

Well, creating a global object strikes me as problematic since you might process multiple requests at once. Creating an object in the session state would be a little better since MVC serializes all requests in a session by default, but you could still run into concurrency problems in the future. Honestly, I think the best way is just to create the object in every action method that needs it.

Peter Ruderman
+2  A: 

You could use the Initialize method. Have a base controller that defines this protected property and in the Initialize method set the value. Then as all your controllers derive from the base controller they will have access to the property.

Darin Dimitrov
+1 This is also a very nice approach even though it will make things a bit less transparent for my taste. Of course it has to be coupled with base controller class as well. But it will actually work faster than using action filters. (I'd vote twice if I could, because this is the optimal way of doing it)
Robert Koritnik
+3  A: 

Use action filter and base controller functionality

The easiest way would be to create an action filter. Do these:

  1. Create a base controller class that defines this property
  2. Write an action filter that is able to parse request's query string and populates base controller's property. Don't forget to set this action filter attribute's inheritance to true.
  3. Attach action filter (attribute) to controller class

This way you will be able to make query string processing generic as well as automated, because you won't have to attach this action filter to all actions. It will already be attached to all child controller classes by means of inheritance.

Robert Koritnik
+1 Aaah, beat me by a split second :-)
Jakob Christensen
@Jakob: Happens even to the best of... you... ;)
Robert Koritnik
A: 

One way to do this is to use action filters. You can see a simple example here.

Jakob Christensen