Reputation: 765
I am trying to make a class that has two constructors, both with three arguments. One constructor is called if a user will be added, the other if the user is just being updated:
public class RequestController : IRequestController
{
public RequestController(IConnector, IAddRequestHandler, IAddReplyHandler) { ... }
public RequestController(IConnector, IUpdateRequestHandler, IUpdateReplyHandler) { ... }
}
I am aware that Unity doesn't appreciate multiple constructors of the same length and I have been trying to resolve this issue. So far, I can only find detailed explanation for if there are multiple constructors of length 1. This is what I have so far:
var container = new UnityContainer();
container.RegisterType<IRequestController, RequestController>("addConstructor",
new InjectionConstructor(typeof(IMQSeriesConnector), typeof(IAddRequestHandler), typeof(IAddReplyHandler)));
container.RegisterType<IRequestController, RequestController ("updateContructor",
new InjectionConstructor(typeof(IConnector), typeof(IUpdateRequestHandler), typeof(IUpdateReplyHandler)));
I think the next step is something along the lines of:
container.Resolve<IRequestController>("addConstructor",
new DependencyOverride(typeof(IConnector), typeof(IAddRequestHandler), typeof(IAddReplyHandler)));
container.Resolve<IRequestController>("updateConstructor",
new DependencyOverride(typeof(IRequestController), typeof(IAddRequestHandler), typeof(IAddReplyHandler)));
But this, of course, does not work. What am I missing for the "container.Resolve" piece?
Upvotes: 0
Views: 643
Reputation: 172646
I am trying to make a class that has two constructors, both with three arguments
This is where you go wrong. Your application components should have exactly 1 public constructor. Having multiple is an anti-pattern, as explained here. In short:
multiple constructors are redundant, ambiguous, make your DI configuration fragile, and lead to maintainability issues.
In your case you have one constructor with an IAddRequestHandler
dependency and a different constructor with an IUpdateRequestHandler
dependency.
What you probably are trying to achieve is to build an object graph with only dependencies that are required for the current request, but this doesn't make sense for multiple reasons.
First of all, since injection constructors should be simple, the construction of object graphs (even really big ones), should be really fast. So trying to optimize this does not make sense. From that point of view, your controller should have one constructor, and it should accept (and require) all the dependencies that class needs.
It might also indicate that your controller actually does too much and therefore violates the Single Responsibility Principle. You probably should split up this controller into two separate classes, each with (still) one constructor. This immediately makes your object graph narrower and smaller as well.
Upvotes: 1