Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there 2 constructors in the Default AccountController provided by the MVC?

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

        //---
    }

This is easy to understand.

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.

Thanks for helping

like image 475
Richard77 Avatar asked Dec 08 '25 10:12

Richard77


1 Answers

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

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

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 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.

like image 60
Mark Seemann Avatar answered Dec 10 '25 07:12

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!