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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With