Is there any benefit of asp.net web api controller interfaces?

蓝咒 提交于 2019-12-13 01:22:58

问题


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;
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/15398858/is-there-any-benefit-of-asp-net-web-api-controller-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!