Sharing code between ASP.NET MVC Controllers
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 开发者_C百科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.
I'd factor out in to a helper class or something. From what you have described the functionality helps the controllers/
The choices seem to be base controller or helper class. You could take control of controller creation and inject the helper into whichever controllers need it.
精彩评论