问题描述
我看到很多人谈论在他们的 ASP.NET MVC 项目中使用基本控制器.我见过的典型示例是为了日志记录或 CRUD 脚手架而这样做的.基本控制器类还有哪些其他好的用途?
I've seen a lot of people talk about using base controllers in their ASP.NET MVC projects. The typical examples I've seen do this for logging or maybe CRUD scaffolding. What are some other good uses of a base controller class?
推荐答案
基本控制器类没有什么用处.
There are no good uses of a base controller class.
现在听我说.
Asp.Net MVC,尤其是 MVC 3 有大量的可扩展性钩子,它们提供了一种更加解耦的方式来向所有控制器添加功能.由于您的控制器类非常重要并且是应用程序的核心,因此让它们保持轻量、敏捷和松散耦合非常重要.
Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.
日志基础设施属于构造函数,应该被注入通过 DI 框架.
Logging infrastructure belongs in aconstructor and should be injectedvia a DI framework.
CRUD 脚手架应由代码生成或自定义模型元数据提供程序.
CRUD scaffolding should be handled bycode generation or a customModelMetadata provider.
全局异常处理应该是由自定义 ActionInvoker 处理.
Global exception handling should behandled by an custom ActionInvoker.
全局查看数据和授权应该由动作过滤器处理.使用全局操作过滤器更容易在MVC3中.
Global view data and authorizationshould be handled by action filters.Even easier with Global action filtersin MVC3.
常量可以放在另一个名为 ApplicationConstants 的类/文件中.
Constants can go in another class/file called ApplicationConstants or something.
基本控制器通常由没有经验的 MVC 开发人员使用,他们不了解 MVC 的所有不同的可扩展性部分.现在不要误会我的意思,我不是在评判和与出于所有错误原因使用它们的人一起工作.它只是经验,为您提供更多工具来解决常见问题.
Base Controllers are usually used by inexperienced MVC devs who don't know all the different extensibility pieces of MVC. Now don't get me wrong, I'm not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.
我几乎可以肯定,除了基本控制器类之外,没有其他可扩展性挂钩无法解决的问题.不要采用最紧密的耦合形式(继承),除非有重要的生产力原因并且您没有违反 Liskov.我更愿意使用 <1 秒在我的控制器中输入一个属性 20 次,例如 public ILogger Logger { get;放;}
比引入以更重要的方式影响应用程序的紧密耦合.
I'm almost positive there isn't a single problem you can't solve with another extensibility hook than a base controller class. Don't take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don't violate Liskov. I'd much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; }
than introduce a tight coupling which affects the application in much more significant ways.
甚至像 userId 或多租户密钥这样的东西也可以放在 ControllerFactory 而不是基本控制器中.基础控制器类的耦合成本是不值得的.
Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.
这篇关于什么是 ASP.NET MVC 中基本控制器类的良好候选者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!