Aparan
Aparan

Reputation: 1273

MVC controller: Common object in methods

In my mvc3 controller, a particular object is used in several methods. Should I declare it as a member variable of the controller and provide properties to access that? But what happens with each time one of the action method is called from the client? Will the object be created again and again? Is there any particular advantage for the above mentioned method, if that is the case? Is declaring MySpclClass as singleton class, a good option in this case?

In short, is there any advantage in using this method:

 public class MyController : Controller
    {
         MySpclClass myObject=new MySpclClass();


        public ActionResult DoFirst(int id)
        {
          ....................
          myObject.doOneThing();
          ....................  
        }

        public ActionResult DoSecond(int id)
        {
          ....................
          myObject.doAnotherthing();
          ....................  
        }
    }

over this method:

public class MyController : Controller
        {       

            public ActionResult DoFirst(int id)
            {
             MySpclClass myObject=new MySpclClass();
               ....................
              myObject.doOneThing();
              ....................  
            }

            public ActionResult DoSecond(int id)
            {
             MySpclClass myObject=new MySpclClass();                            
              ....................
              myObject.doAnotherthing();
              ....................  
            }
}

And what about this:

 public class MyController : Controller
            {       

                 MySpclClass myObject;
                public ActionResult DoFirst(int id)
                {
                 myObject=new MySpclClass();
                   ....................
                  myObject.doOneThing();
                  ....................  
                }

                public ActionResult DoSecond(int id)
                {
                 myObject=new MySpclClass();                            
                  ....................
                  myObject.doAnotherthing();
                  ....................  
                }
    }

EDIT: Is declaring MySpclClass as singleton class, a good option in this case as Rajansoft1 suggested ? Need suggestions on this.

Upvotes: 2

Views: 2145

Answers (7)

rajansoft1
rajansoft1

Reputation: 1356

you can use the below code

public class MyController : Controller
{
 private readonly IMySpclClass _mySpclClass;
public void MyController(IMySpclClass mySpclClass)
{
     _mySpclClass = mySpclClass;
}
public ActionResult DoFirst(int id)
{
    _myObject.doOneThing(); // Set some properties on the model that are stored on the view as hiddenfields and will be posted back to the "DoSecond" action.
    return view("MyView", myObject);
}

[HttpPost]
public ActionResult DoSecond(MySpclClass myObject) 
{            
   _myObject.doAnotherthing(); // Uses the properties that where stored on the view and posted back again.
    return view("MyView", myObject);
}
}

 //and add the below code to ninject factor class

 _kernel.Bind<IMySpclClass >().To<MySpclClass >().InSingletonScope();

 //also intialize _kernel above as shown

 private static IKernel _kernel;
    public static void Register()
    {
        _kernel = new StandardKernel();
        AddBindings();
    }

    private static IKernel Instance
    {
        get { return _kernel; }
    }
     and write all the bindings in the AddBindings() function

Upvotes: 0

James
James

Reputation: 82096

Well if you consider the fact the controller is created per request then it all depends on whether you need myobject to retain some sort of state across those requests. If you just need an instance of that object (with it's default state) then I would go with the first approach as it's more DRY than the others.

Alternatively, if myobject is just a helper you could consider making it a static singleton.

Upvotes: 1

ikwillem
ikwillem

Reputation: 1064

This is why you use models.

public class MyController : Controller
{
    public ActionResult DoFirst(int id)
    {
        MySpclClass myObject = new MySpclClass(); // The model
        myObject.doOneThing(); // Set some properties on the model that are stored on the view as hiddenfields and will be posted back to the "DoSecond" action.
        return view("MyView", myObject);
    }

    [HttpPost]
    public ActionResult DoSecond(MySpclClass myObject) 
    {            
        myObject.doAnotherthing(); // Uses the properties that where stored on the view and posted back again.
        return view("MyView", myObject);
    }
}

Upvotes: 2

Mharlin
Mharlin

Reputation: 1705

The controller will be instantiated each time an action method is called so in my opinion you should use

public ActionResult DoFirst(int id) 
{
              MySpclClass myObject=new MySpclClass();
              myObject.doOneThing();
}

It makes it more clear when the declaration of the variable is closer to the usage. If it's not used from all action methods there is no point of instantiating it.

Upvotes: 1

Knaģis
Knaģis

Reputation: 21475

Your second option (without a class level field) is the best because it does not create the impression that the field value is saved between requests (it isn't since the framework will recreate the Controller instance for every request).

However if the field is used in most of your methods you might consider using the field but then you should create a property for accessing it like this so that it is automatically instantiated whenever needed (or instantiate the field always in the constructor).

private MySpclClass myObject;
public MySpclClass MyObject
{
    get
    {
        if (this.myObject == null)
            this.myObject = new MySplClass();
        return this.myObject;
    }
}

Upvotes: 1

rajansoft1
rajansoft1

Reputation: 1356

You can use Dependency injection to deal with these issues. one of the best tool for dependency injection is ninject which creates an instance of the object once and provide it whenever it is needed in any controller, you just need to configure it once.

if you are new to ninject you can find it here http://www.ninject.org/

Upvotes: 3

Mathew Thompson
Mathew Thompson

Reputation: 56429

There's no advantage, unless you were calling multiple ActionResult methods on one request.

Each request will instantiate a new instance of your Controller, so you object will be recreated at that point anyway.

Upvotes: 3

Related Questions