gpt4 book ai didi

c# - 为什么 Asp.net web api Controller 不派生自 IController

转载 作者:太空狗 更新时间:2023-10-29 20:17:53 28 4
gpt4 key购买 nike

在 ASP.net MVC4 中,有一个 Web API 的"new"概念,用于在您的数据模型上公开 CRUD 功能。这些 Controller 的基类是 DataController,它派生自 ApiController

不幸的是,这个 ApiController 不是从 IController 派生的,这是有问题的,因为这些请求不能通过你的普通自定义 Controller 工厂处理,因为它们应该返回一个IController 的实例。

有谁知道这背后的原因,因为我不明白为什么你的 MVC 项目中会有一个 Controller 不是从 IController 派生的,因为这会破坏你的自定义 Controller 工厂,因为它不是能够实例化项目中的每个 Controller 。

简而言之,由于这种继承,您无法使用 DI 容器注入(inject)依赖项。

最佳答案

我也向 Microsoft 发送了同样的问题,并得到了 Eilon Lipton 的以下回复(对此表示感谢):

The short story is that while ASP.NET MVC and ASP.NET Web API share a lot of the same design concepts (dependency injection, lots of interfaces to plug in custom implementations, and easy testability), they build on different underlying HTTP stacks. MVC builds on the System.Web stack that has been used in ASP.NET for over 10 years. Web API builds on the new System.Net.Http stack which offers greater flexibility for hosting (IIS + custom hosts + unit test hosts) as well as better testability and extensibility. If you compare IController and IHttpController you’ll see that one uses System.Web up and down the stack, and the other doesn’t use it at all.

Regardless of any of this, all the technologies built on the ASP.NET stack – MVC, Web Forms, Web API, Web Pages (and Razor) – will continue to work side-by-side within an application, allowing you to choose the right pieces to build each part of your application. While individual implementations of components within each piece are not interchangeable, they can each be wired up to the same services, such as dependency injection systems, logging tools, data providers, and so forth.

Once we publish our post on this subject I think that should clarify things further.

关于c# - 为什么 Asp.net web api Controller 不派生自 IController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9496262/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com