0

I'm working on ASP.NET MVC application & have a quick design question for you. So I need to implement a common functionality for all my controllers (well, most of them). I don't want to repeat the same logic in all the controllers. What'd be the ideal approach in the best interest of MVC?

I found people saying create base controller and inherit it in your controllers. But when I visualize a controller, I can see it'd contain only action methods that return some content/views - Correct me if I'm wrong.

   OneController
   {
       ActionMethod A1
       {
           //Code to return list of objects for the given integer value. So it calls database stored procedure.
       }
   }

...multiple such controllers are there.

I'd still like to have A1 exists in the OneController, just put its logic somewhere common place.

Also some people suggest to create just plain Helper class to place the common method.

Could you please suggest me what approach will be better (Or any other appropriate approach)? Thanks.

DataPy
  • 209
  • 2
  • 10
  • Controller can contain action methods and methods if you want, base controller class is a good option to do you want – DanielVorph Nov 03 '16 at 22:36

1 Answers1

1

I agree with you that, most of the times, it only makes sense to inherit from base controllers when we're talking about Actions or methods that are really related. But of course, you can just use base controllers for everything. Your choice.

Other than that, you have 2 options. For classes that have little to no chance of being polymorphic (change behavior depending on the implementation), you are fine to create static classes and just use them inside your controllers. An example would be a class that does math calculations, these are not that polymorphic by nature.

For all the other cases, I'd strongly suggest that you use dependency injection. One of the reasons being that unit testing will become way easier. Here's a guide on how to do it for MVC 4 onwards using the built in engine: https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection. If you don't want to use it and use Ninject or Simple Injector, you can implement your own ControllerActivator and use Ninject, for instance, to get an instance of your controller.

When using dependency injector, normally your controller would get the dependencies in the constructor, like this:

public class StoreController : Controller
{
    private IStoreService service;

    public StoreController(IStoreService service)
    {
        // service in an injected dependency
        this.service = service;
    }
 }

For more information, Google ASP.NET dependency injection.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • Thanks guys for your inputs. I actually ended up placing the common method in BaseRepository, that my all other repositories classes can inherit. – DataPy Nov 07 '16 at 20:38