开发者

C#: On method call event? (Refactor my code)

开发者 https://www.devze.com 2023-03-03 15:46 出处:网络
I have a controller, where every Action share a certain parameter. Also the first line in every method is common amongst the actions.

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 t开发者_StackOverflowo 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?


Make "var object" member of your class and initialize it in a constructor.


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


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.


Something like this?

public class MyClass
{
   private _YourObject;

   public MyClass(string routeName)
   {
      _yourObject =  _repository.Get(routeName);
   }
   public ActionResult Add()
   {
      ...
   }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消