3

I'm a huge fan of coding against interfaces. In the WCF world, this highly emphasized on every service. However, I'm getting deeper into ASP.NET Web Api, as an extension of MVC 4, I was curious to see if there was some typical reasoning to have your controller implementations inherit from an interface.

I know the default settings for ASP.NET Web Api look something like this

public class TestsController : ApiController
{

    public IEnumerable<string> Get()
    {
        var testValues = new List<string>
            {
                "Something",
                "Welcome to the top of the world"
            };
        return testValues;
    }
}

As opposed to this WITH a cooresponding interface (or interfaces).

public class TestsController : ApiController, ITestsController 
{

    public IEnumerable<string> Get()
    {
        var testValues = new List<string>
            {
                "Something",
                "Welcome to the top of the world"
            };
        return testValues;
    }
}
Max Alexander
  • 5,471
  • 6
  • 38
  • 52

1 Answers1

4

I think there is no value in using an interface like that for a controller. WCF relies a lot on interfaces because it's a common thing for SOAP services, and it is something used for generating the contracts in WSDL. However, an HTTP Web API does not have that kind of contract, and it is typically a bad practice to have it. Also, interfaces are common when you need to use dependency injection and unit testing because they allow you to easily fake dependencies. However, I don't think you would inject a controller as dependency into another class, so it does not make sense there too.

Pablo Cibraro
  • 3,769
  • 3
  • 25
  • 17
  • That's what I figured. I couldn't see much use of programming a controller tightly to an interface in this framework, particularly because the objects leave and enter the service as JSON (usually) and are out in the wild of HTTP. I guess this concept abandons the idea of separate assemblies depending on each other's forward facing type safety and bounded contracts. – Max Alexander Mar 14 '13 at 14:32
  • 2
    I was wondering the same thing, but wouldn't interfaces be useful to enforce versioning? API v1, v2, etc? – inliner49er Aug 29 '20 at 15:10