Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing code between ASP.NET MVC Controllers

Tags:

c#

asp.net-mvc

I've got a few controllers here at work that contain methods I can use in other controllers.

I considered moving out some of the common functionality to a base controller which these could then inherit from. The problem with this is that I’d have methods I need in multiple base controls which I’d not be able to access. (Because we can't inherit from multiple base controllers).

My other idea is to move out the common functionality into their own classes, outside of the Controller folder.

What would you do? Is there a great way in ASP.NET MVC to share code like this that I don't yet know about?

like image 249
Jamie Dixon Avatar asked Nov 02 '09 11:11

Jamie Dixon


1 Answers

There's a rule of thumb about object-oriented programming that you should favor composition over inheritance, and it fits very well into this scenario.

I would make one or more services that encapsulate the methods in question, and then consume those services from the Controllers.

For extra points, extract an interface from the service(s) in question, and inject the interface into the Controllers for maximum Separation of Concerns.

like image 121
Mark Seemann Avatar answered Sep 27 '22 21:09

Mark Seemann