Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I reuse NonAction methods between controllers
    text
    copied!<p>Lets say I have a controller class like this.</p> <pre><code>public class InStorePickupController : Controller { private readonly IToppingService _toppingService; public InStorePickupController(IToppingService toppingService) { this._toppingService = toppingService; } public ActionResult GetPizza() { var pizzaModel = new PizzaModel(); pizzaModel = MakePizza(pizzaModel); return View(pizzaModel); } [NonAction] public PizzaModel MakePizza(PizzaModel pm) { var toppings = _toppingService.GetAllToppings(); //roll out dough //put toppings on pizza //bake pizza return pm; } } </code></pre> <p>But I also have another controller class where I want to use the same 'Make Pizza' non action.</p> <pre><code>public class DeliveryController : Controller { private readonly IToppingService _toppingService; public DeliveryController(IToppingService toppingService) { this._toppingService = toppingService; } public ActionResult GetPizza() { var pizzaModel = new PizzaModel(); pizzaModel = MakePizza(pizzaModel); return View(pizzaModel); } } </code></pre> <p>This is a simple example but it matches my real situation very closely. The only difference is that:</p> <ol> <li>I have several non action methods and they are fairly involved (lots of calculations).</li> <li>I have quite a few controllers that need access to these non actions. This isn't controller creep so consolidating them won't work.</li> <li>Each controller has quite a few necessary services in the constructor.</li> </ol> <p>I could have each controller inherit from a base controller class but I keep getting complaints about a parameter-less constructor.</p> <p>What about static classes? </p> <p>I just need a little guidance. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload