Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple controller constructors when injecting dependencies using Unity.Mvc5

I'm very new to dependency injection and I've just set up Unity.Mvc5 and has some success with it. But now I face the problem of multiple contructors in my controller class. I already have constructors that handle my UserManager and following tutorials I understand I need another constructor to instantiate my interface. When I do this however, I get the following error:

The type OrganisationController has multiple constructors of length 1. Unable to disambiguate.

A snippet from my controller:

    private IPush _pushMessage;

    // Here is the problem!
    public OrganisationController(IPush pushMessage)
    {
        _pushMessage = pushMessage;
    }

    public OrganisationController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
    }

    public OrganisationController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
        var provider = new DpapiDataProtectionProvider("MyApp");
        UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset"));
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }

And my UnityConfig.cs as follows:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterType<IPush, PushMessage>();
        container.RegisterType<IController, OrganisationController>();
        container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
        container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

I am not sure how to tell Unity that I have another constructor being used to implement an interface.

like image 740
barnacle.m Avatar asked Mar 17 '16 13:03

barnacle.m


2 Answers

When using DI, constructors are specifically for DI. There is no reason to create alternate constructors (especially on controllers, since the only caller is the ControllerFactory which delegates the call to the DI container).

In fact, using multiple constructors with dependency injection is anti-pattern and should be avoided.

Related: Rebuttal: Constructor over-injection anti-pattern

like image 50
NightOwl888 Avatar answered Nov 20 '22 13:11

NightOwl888


While I agree with other answer by @NightOwl888. In some cases you may want to have multiple constructors.

Have you tried InjectionConstructor attribute?

[InjectionConstructor]
public OrganisationController(IPush pushMessage)
{
    _pushMessage = pushMessage;
}
like image 2
AksharRoop Avatar answered Nov 20 '22 14:11

AksharRoop