Reputation: 345
I have a controller, where every Action share a certain parameter. Also the first line in every method is common amongst the actions.
E.g.
public ActionResult Add(string routeName) //Common parameter
{
var object = _repository.Get(routeName); //Common line
...
}
How can I refactor this, enabling me to remove
var object = _repository.Get(routeName);
and/or the parameter, but still be able to access them like before?
Edit: I'm using IoC to inject all my repositories into the class, so the controller is kind of not avaliable.
Also, I'm using routes:
E.g.
routes.MapRoute("Object-Add", "{foo}/{object}/add", new { controller = "Object", action = "Add" });
Is that perhaps also a problem?
Upvotes: 0
Views: 155
Reputation:
Something like this?
public class MyClass
{
private _YourObject;
public MyClass(string routeName)
{
_yourObject = _repository.Get(routeName);
}
public ActionResult Add()
{
...
}
}
Upvotes: 0
Reputation: 67
Just making it a property in your class would be best. I'd use lazy initialization, that way the object gets created at the same time it normally would in runtime, but can be reused in each of the actions.
Upvotes: 0
Reputation: 35219
Make "var object" member of your class and initialize it in a constructor.
Upvotes: 1
Reputation: 4114
put this code in the constructor of controller class the parameter you can get from request and store in the field of controller class
Request.QueryString
Upvotes: 0