【问题标题】:Why are there 2 constructors in the Default AccountController provided by the MVC?为什么MVC提供的Default AccountController中有2个构造函数?
【发布时间】:2009-12-31 04:51:25
【问题描述】:

这是框架生成的默认 AccountController.cs

public class AccountController : Controller
{
    public IFormsAuthentication FormsAuth { get; private set; }
    public IMembershipService MembershipService { get; private set; }

    public AccountController()
        : this(null, null)
    {
    }
    public AccountController(IFormsAuthentication formsAuth, IMembershipService membershipService)
    {
        FormsAuth = formsAuth ?? new FormsAuthenticationService();
        MembershipService = membershipService ?? new AccountMembershipService();

        //---
    }

这很容易理解。

public AccountController(IFormsAuthentication formsAuth, 
        IMembershipService membershipService)
    {
        FormsAuth = formsAuth ?? new FormsAuthenticationService();
        MembershipService = membershipService ?? new AccountMembershipService();
    }

这是什么?它的目的是什么?它是帐户控制器特有的还是其他控制器的要求?而且,我为什么要把它合并到我的项目中?

public AccountController()
        : this(null, null)
    {
    }

他们似乎在另外两个地方使用了这种类型的构造函数。

感谢您的帮助

【问题讨论】:

    标签: asp.net-mvc dependency-injection constructor


    【解决方案1】:

    这实际上是 Bastard Injection 反模式的实现。

    这个想法是支持 构造函数注入 以允许依赖注入 (DI),同时仍为默认行为提供默认构造函数。

    实际上没有必要有默认构造函数,但如果你省略它,你必须提供一个自定义的 IControllerFactory,因为 DefaultControllerFactory 假定所有控制器都有默认构造函数。

    ASP.NET MVC 在构建时考虑了 DI,但我想为了简单起见,项目模板使用了混蛋注入模式以避免将特定的 IControllerFactory 强加给开发人员。

    【讨论】:

      【解决方案2】:
      1. 如果您使用 DI 框架(如 Unity)并通过容器激活控制器,它可能找不到依赖项并使用默认构造函数(在这种情况下)。

      2. 如果你想使用泛型,比如... where T : IController, new(),你需要一个默认构造函数。

      【讨论】:

        【解决方案3】:

        拥有默认(无参数)构造函数的另一个原因是Reflection

        System.Reflection 命名空间中的类与 Type 一起允许您获取有关已加载的 assemblies 以及其中定义的类型的信息,例如 classesinterfacesvalue types。您还可以使用反射在运行时创建类型实例,并调用和访问它们。

        有时您可能需要创建该类型的临时对象以反映其属性或方法,但不希望或不需要创建真实对象的开销 - 特别是如果这需要访问数据库或例如远程服务。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-19
          • 2014-03-21
          • 1970-01-01
          • 2012-03-12
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          相关资源
          最近更新 更多