2

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.

1
  • For every new request, MVC will create a new instance of your controller class. Commented May 29, 2013 at 10:55

7 Answers 7

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I just needed to ensure that.
3

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/

8 Comments

Dependency injection will still create an instance per-request.
@mattytommo - that depends on how you configure the injector. it is possible to configure it to use singleton etc.
you can create singleton instance like this _kernel.Bind<IMapperService>().To<MapperService>().InSingletonScope();
you can configure most IoC containers to use singleton pattern or other "per lifetime scope" style options
@rajansoft1: can you explain how to use the singleton pattern in my case? With some code if you can.
|
2

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);
    }
}

Comments

1

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;
    }
}

Comments

1

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.

Comments

1

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.

Comments

0

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

Comments

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.