Would creating a controller's interface a bad idea? I have a controller that derived from ApiController, so knowing that you can only derived one class to a class but able to derived one or more interface to a class.

public class FooController : ApiController

My problem is I have code that is in another controller that can be used in FooController. I don't want to repeat the code so I'm thinking to create a base class that will hold common codes and create an interface for the base class. Would this be considered a bad idea or any suggestion on this?

  • 1
    I don't understand why you want to create an interface, if you propose to create a common base controller. – Gaste Sep 19 '16 at 8:19
  • @Gaste because the controller that will be using the common codes in base controller is already derived in ApiController – rpmansion Sep 19 '16 at 8:48
  • 1
    I thought you want something like class BaseController : ApiController, which implements the common methods. Then inherit the two controllers using the common code from BaseController: class FooController : BaseController and class BarController : BaseController – Gaste Sep 19 '16 at 8:52
  • @Gaste and if the controller is not derived in ApiController only in Controller? my problem is I have two controllers that use common codes. First controller is derived in Controller; Second controller is derived in ApiController. If I'll be making BaseController derived from ApiController then I would be having problem using it with the controller that does not derived from ApiController but Controller – rpmansion Sep 19 '16 at 9:45
  • 1
    A interface only specifies the signatures of the methods, not the implementation. So if you specify the commonly used methods in an interface ICommonController, you still have to implement the interface in all controllers: class FooController : ApiController, ICommonController and class BarController : Controller, ICommonController. Depending on what the commonly used code does, you could however move it into another class (and possibly abstract the behaviour using an interface), which is then injected as dependency in the controllers. – Gaste Sep 19 '16 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.