5

My application has MVC controllers and WebApi controllers. Up to this point, I've been able to push any logic shared between the controllers into a BaseController and BaseApiController, respectively.

Now I have a situation where both an API controller and MVC controller are doing the same thing - registering a new user account. This process is a bit complex because I have a multi-tenant application, and looks something like this:

// MVCController : BaseController
public ActionResult Register(RegisterModel model) {
      // see if the model is valid
      // check and make sure the credentials check out with policy requirements
      // add the user to the user table if they aren't already there
      // create a tenancy
      // assign cookie
 }

Most of the actual work is pushed off into the service layer, but the calls and conditions take up about 20 lines of code that I'd rather not copy and paste into the analogous WebApi controller.

So I'm wondering if I can somehow have both my BaseController and BaseApiController inherit from a generic controller where I can put this auth code. What's the recommended approach here?

2 Answers 2

5

Unless I am missing something from your question, I would refactor that piece of code into a Util class that lives in your UI project. Then both your MVC controller and WebAPI controller can call it.

This approach is in-line with Composition over inheritance design principle.

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

1 Comment

Yeah, I'd pull the account registration code into another class/interface so you can re-use it. If you define an interface for it you'll make your code more testable and in line with inversion of control principles.
0

If you cannot move the logic out into it's own library and then share it then I would probably see about calling the web api from mvc. See this post for an example on doing that: https://stackoverflow.com/a/13206631/426422

4 Comments

Yeah... I definitely don't like the thought of pushing it into its own library, or pushing the call into HTTP territory. I'd rather just duplicate the code if those are my only two options :/
What are you worried about?
Solution overhead with the first approach, performance with the second. I know it's minimal but I'd rather duplicate code than add a bunch of milliseconds. Am I crazy?
Web API is made to be streamlined. Duplicating code is usually bad. Have a look at this article: odetocode.com/blogs/scott/archive/2013/07/01/…

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.