asp.net web api控制器接口有什么好处吗? [英] Is there any benefit of asp.net web api controller interfaces?

查看:181
本文介绍了asp.net web api控制器接口有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢接口编码。在WCF世界中,这一点非常强调每项服务。但是,我正在深入研究ASP.NET Web Api,作为MVC 4的扩展,我很想知道是否有一些典型的推理让你的控制器实现从接口继承。

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.

我知道ASP.NET Web Api的默认设置看起来像这样

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


推荐答案

我认为使用类似于控制器的接口没有任何价值。 WCF很大程度上依赖于接口,因为它是SOAP服务的常见问题,它是用于在WSDL中生成契约的东西。但是,HTTP Web API没有这种合同,拥有它通常是一种不好的做法。此外,当您需要使用依赖项注入和单元测试时,接口很常见,因为它们允许您轻松伪造依赖项。但是,我认为你不会将控制器作为依赖注入另一个类,所以它也没有意义。

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.

这篇关于asp.net web api控制器接口有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆