为什么在MVC提供的默认AccountController中有2个构造函数? [英] Why are there 2 constructors in the Default AccountController provided by the MVC?

查看:1059
本文介绍了为什么在MVC提供的默认AccountController中有2个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

here's the default AccountController.cs that's generated by the framework.

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

这是什么?它的目的是什么?是特别是帐户控制器还是其他控制器的要求?

What's this? What's its purpose? Is it particular to the Account Controller or is it a requirement for other controllers? and, why should I incorporate it in my project?

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

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

They seem to use this type of constructors in two other places.

感谢您的帮助

推荐答案

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

This is actually an implemenation of the Bastard Injection anti-pattern.

这个想法是支持构造函数注入 DI),同时仍然提供默认行为的默认构造函数。

The idea is that Constructor Injection is supported to allow Dependency Injection (DI), while still providing a default constructor for default behavior.

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

It's really not necessary to have the default constructor, but if you omit it, you must supply a custom IControllerFactory, as the DefaultControllerFactory assumes that all Controllers have default constructors.

ASP.NET MVC是用DI构建的,但我想,为了保持简单,Bastard注入模式用于项目模板,以避免对开发人员强制使用特定的IControllerFactory。

ASP.NET MVC is built with DI in mind, but I guess that to keep it simple, the Bastard Injection pattern was used for the project template to avoid forcing a specific IControllerFactory upon developers.

这篇关于为什么在MVC提供的默认AccountController中有2个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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