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.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With