Lets say I have a controller class like this.
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;
}
}
But I also have another controller class where I want to use the same ‘Make Pizza’ non action.
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);
}
}
This is a simple example but it matches my real situation very closely. The only difference is that:
- I have several non action methods and they are fairly involved (lots of calculations).
- I have quite a few controllers that need access to these non actions. This isn’t controller creep so consolidating them won’t work.
- Each controller has quite a few necessary services in the constructor.
I could have each controller inherit from a base controller class but I keep getting complaints about a parameter-less constructor.
What about static classes?
I just need a little guidance. Thanks.
A base class is potentially the way to go, whereby you could do something like:
Or, introduce a new service, the
IPizzaService:Which you can inject into your controller instead.