Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApiController and Controll inherit from same base class

Tags:

asp.net-mvc

I have multiple controllers and apicontrollers in my project.

How to make both types of controllers inherit a base class, as there is more than some methods, that I need in both?

like image 284
SpoksST Avatar asked Feb 03 '26 03:02

SpoksST


1 Answers

Composition might be a better option.

Basically instead of inheriting to gain the functionality stick it in a common class, that can be included as a property in both the Api and standard controller.

You can then inject the dependancy into both.

For example:

public class CommonControllerLogic : ICommonControllerLogic 
{
  public ActionResult SomeSortOfMethod() 
  {
     // etc..
  }
}

public class MobileApiController: ApiController 
{
  public ICommonControllerLogic CommonControllerLogic  {get;set;}

  // etc..
}

public class HomeController: Controller 
{
  public ICommonControllerLogic CommonControllerLogic  {get;set;}

  // etc..
}

Composition is often favoured over inheritence, there are loads of articles on it, just do a quick google search, have a read of this article.

like image 198
shenku Avatar answered Feb 05 '26 23:02

shenku