Jasmine
Jasmine

Reputation: 5326

readonly field assigned in constructor and also clearing it doesn't clear values

I have a readonly field like this

private readonly IManageSessionContext _manageSessionContext;

public ManageController(IManageSessionContext manageSessionContext)
{
      _manageSessionContext= manageSessionContext;
      //doing some operations
      _manageSessionContext.Clear();
}

Doesn't clear the session or object values of this read only field. Why? But when I place it before the return statement in Index View, it does clear.

Upvotes: 0

Views: 135

Answers (1)

Nico
Nico

Reputation: 12683

You have not provided any of the code for your Index action however in your example you are calling _manageSessionContext.Clear(); in your constructor.

The constructor is called when the class ManageController is created passing in the IManageSessionContext dependency. The constructor is always called first where you are first Clear()ing the IManageSessionContext (whatever that is).

My hunch is there is more work being done in the IManageSessionContext between the constructor of ManageController class being called and the return of your Index action method.

For example. Take the code snippet below

public class ManageController
{
    readonly IManageSessionContext _manageSessionContext;

    public ManageController(IManageSessionContext manageSessionContext)
    {
        _manageSessionContext = manageSessionContext;

        //some operations..
        _manageSessionContext.Clear();
    }

    public ActionResult Index()
    {
        _manageSessionContext.DoSomeWorkWithManagedContext();

        _manageSessionContext.Clear();

        return View();
    }

}

The code executes the constructor first ManageController(IManageSessionContext manageSessionContext) which eventually calls the Clear() method for the IManageSessionContext

Next the action Index executes, Index DoSomeWorkWithManagedContext() is called which changes the IManageSessionContext dependency. Then the Index method re-calls the Clear method.

Now in the chain would go

  1. Constructor Called -> Clear's session
  2. Index Method (action) called Does work in the session -> Clears session

As the constructor is executed first any additional work with the object will change the object thus requiring a Clear before closing the Index method.

Hope this makes sense.

Upvotes: 1

Related Questions