views:

145

answers:

1

I have a edited RESTful wizard based upon Shoulders of Giants | A RESTful Wizard Using ASP.Net MVC… Perhaps? . This wizard has a CANCEL button which, when pressed, fires the code below.

// If the user cancels, drop out altogether
if (!string.IsNullOrEmpty(CANCEL_BUTTON)) {
     Session.Remove(VACANCYWIZARD_SESSION_KEY);
     repository._entities.ObjectStateManager.GetObjectStateEntry(inProgressVacancyWizard.Vacancy).Delete();
     return this.RedirectToAction("Index", "Home");
}

Now, to be able to call SaveChanges() after the cancel button I have to manually delete the entry from the wizard from my ObjectStateManager. But when you cancel the wizard by just manually returning to the home page it stays in and a next call to _entities.SaveChanges() will throw an exception that it cannot Save the object, from the wizard progress to the database, since it is still in the object state.

Note that in between the steps of the wizard I do not save anything to the database. I keep it in session state retrieving it each step:

NewVacancy inProgressVacancyWizard = Session[VACANCYWIZARD_SESSION_KEY] as NewVacancy;

Somehow, however, the inProgressVacancyWizard.Vacancy does appear in the ObjectStateManager so I have to delete it else I will get errors about incomplete Vacancies models while the *_entities.SaveChanges() is called for another object*.

Is there a way to cover for this problem?

//edit After some reading I have found out that the fundaments of my repository are not good. As found here. Currently I'm doubting to implement the option mentioned in "One ObjectContext instance per business transaction" in the same article. Would that be a wise thing? I would like to hear some more about it since it will be a major refactor.

public static Repository Instance
    {
        get
        {
            if (instance == null) {
                instance = new Repository();
            }
            return instance;
        }
    }

#region Constructor: Repository()
    /// <summary>
    /// Constructor
    /// </summary>
    private Repository()
    {
        _entities = new DBModelEntitiesNew2();

    }
+1  A: 

It seems like you are using a single ObjectContext instance across multiple requests. Don't do that. It will cause you nothing but misery. It makes your web server stateful. Dispose the ObjectContext after the response is rendered (we do it, indirectly, from Controller.Dispose), and new up a new one for the next request.

Craig Stuntz
Thank you for the response, this is indeed the problem. Though having my wizard pages switching is not that easy. This will be the final answer as it is correct. Though I would love to hear some opinions about the edited information.
bastijn
Why make the repository a singleton? That doesn't make sense to me. You want your web app to be stateless.
Craig Stuntz