9

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?

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I have a slightly different scenario. I have several Web applications whose login controllers have exactly the same code. The differences between these applications' login systems are confined to their web.config files. I would like to have a shared login controller class in a separate project which would be referenced by my Web applications. Is that possible?
Yes. I always code all of my Controllers in separate libraries.
The views I keep in the application entry point. You might want to take a look here: github.com/ploeh/CQRSonAzureDemo
My problem is that I don't want to have 10+ identical copies of the Login.cshtml and _Layout.cshtml files.
4

I'd factor out in to a helper class or something. From what you have described the functionality helps the controllers/

Comments

1

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.

Comments

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.