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?

RobVious
  • 12,685
  • 25
  • 99
  • 181

2 Answers2

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.

kaptan
  • 3,060
  • 5
  • 34
  • 46
  • 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. – Mike Parkhill Dec 18 '13 at 00:56
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

Community
  • 1
  • 1
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
  • 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 :/ – RobVious Dec 17 '13 at 23:42
  • What are you worried about? – Mike Cheel Dec 17 '13 at 23:44
  • 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? – RobVious Dec 17 '13 at 23:45
  • 1
    Web API is made to be streamlined. Duplicating code is usually bad. Have a look at this article: http://odetocode.com/blogs/scott/archive/2013/07/01/on-the-coexistence-of-asp-net-mvc-and-webapi.aspx – Mike Cheel Dec 17 '13 at 23:47