22

I have the same method I call in six controllers. Right now I copy and paste between each of the controllers. All the controllers are in the same namespace. The method returns a bool based on the passed id. For example:

public bool CheckSubmission(int id =0)
{
    Get Records from DB with criteria
    If Record available return true
    else return false
}

I have been away from C++ C# for awhile and can't find how to write these once. I know in Rails I can put the shared functions in ApplicationController. I have seen several Questions on SO about this but not a clear example, they are more along the lines read up on OOP. Any help would be appreciated as I get back into this.

1 Answer 1

37

Create a ControllerBase class that inherits from Controller, place this method in it.

Have your controllers inherit from your base controller - they will get this implementation to use.

public class ControllerBase : Controller
{
  public bool CheckSubmission(int id = 0)
  {
    Get Records from DB with criteria
    If Record available return true
    else return false
  }
}

public class SomethingController : ControllerBase
{
    // Can use CheckSubmission in here
}
Sign up to request clarification or add additional context in comments.

5 Comments

I particularly don't like this suggestion, but agreed, I've used it and it works. Extension methods would be better. static bool CheckSubmission(this Controller controller, int id) { blah; blah; } then you don't need to remember to inherit controllers. It's a pain point to maintain base controllers
better yet, that check should be moved to a distinct service class, to be injected as a (constructor) dependency in any needed controller.
If your shared method is returning an ActionResult, then the inheritance solution is better than an extension solution. This is because the controller object in the extension method cannot access View() or Redirect() or RedirectToAction() "due to its protection level." With inheritance, one can handle a view's controller method: public class SomethingController : ControllerBase { // GET: /Something // Parent object handles Index }
The service suggestion is easy and the best solution as @superjos suggested.
What if you need to access the properties of "SomethingController" from the "CheckSubmission" method. This goes against OOP principals and can't happen. Does this mean you need to go with the copy paste solution anyway?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.