Unity Multiple Constructors of Length 3 - c#

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?

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.

Related

unity create specific instance

I am currently building an application using .net 4.6, MVC 5 and unity 4. I have a controller which looks like the below:
public class ExamController: Controller {
private IEducationService _eduService;
public ExamController(IEducationService eduService) {
_eduService = eduService;
}
}
And Unity injects the service with:
container.RegisterType<IEducationService, EducationService>();
Recently we are adding other Action methods to this controller which will need other services. for example, if I now have an ExperienceService, I could add to that to Unity and change the controller's constructor to take that as well:
public ExamController(IEducationService eduService, IExperienceService _expService )
problem is I don't want both available all the time, they should be available based on which Action method is called. I can make separate constructors for each, but I'm not sure then how to get Unity to make one instead of both, based on which Action method is getting called.
Using multiple constructors on injectables is anti-pattern.
Furthermore, constructors should be simple, so the worry of creating extra objects which aren't used is misguided (unless of course you are violating this rule). Creating objects is very cheap when there is nothing in the constructor but assignment statements, so injecting 1 or even 100 more is probably not going to have a huge impact on performance.
You should also limit the number of services a controller has. If you have more than 3 or 4, you are probably violating the Single Responsibility Principle and should consider refactoring to facade services that each have a single responsibility. The result is that you will have an object graph that looks more like a pyramid with a few dependencies at the top and those dependencies will each have a few more until you get to the bottom where there are none.
Related: Rebuttal: Constructor over-injection anti-pattern
Rather than have the dependencies injected and available to the entire class, you could simply resolve the dependency in the action method where you need it using the ServiceLocator:
var expService = ServiceLocator.Current.GetInstance(typeof(IExperienceService));
You would first need to register Unity's ServiceLocator:
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
Example
Just a quick note: The Service Locator pattern is considered an anti-pattern.

Parameters and Constructors

I've read a lot of detailed things throughout Stack Overflow, Microsoft Developer Network, and a couple of blogs. The general consensus is "A Constructor shouldn't contain large quantities of parameters." So encountering this got me thinking-
Initial Problem: My application contains around fifteen variables that are constantly being used throughout the application. The solution I came up with is I'll create a single class that will inject the values to the Properties.
So this seemed to work quite well, it made my life quite easy as I could pass the object into another class through the Constructor without having to assign all these variables to each method. Except this lead to another issue-
public class ServerParameters
{
// Variable:
private string template;
private string sqlUsername;
private string sqlPassword;
private string sqlDatabase;
private string sqlServer;
public ServerParameter(string _template, string _sqlDatabase, string _sqlServer,
string _sqlUsername, string _sqlPassword)
{
template = _template;
sqlUsername = _sqlUsername;
sqlPassword = _sqlPassword;
sqlDatabase = _sqlDatabase;
sqlServer = _sqlServer;
}
// Link the private strings to a group of Properties.
}
So already this Constructor has become significantly bloated- But now I need to implement even more Parameters.
Problem Two: So I have a bloated Constructor and by implementing other items that don't entirely fit with this particular Class. My solution to this, was to create a subclass or container to hold these different classes but be able to utilize these classes.
You now see the dilemma, which has aroused the all important question- When you can only inherit once, how can you build a container that will hold all of these subclasses?
And why shouldn't you use so many parameters in a Constructor, why is it bad exactly?
My thought on how to implement a Container but I feel like I'm doing it wrong- Because I constantly get Null Reference Exception when I try to use some of these Parameters.
public class VarContainer
{
private ServerParameter server;
private CustomerParameter customer;
public VarContainer(ServerParameter _server, CustomerParameter _customer)
{
server = _server;
customer = _customer;
}
}
I'm assuming it is because the internal class itself isn't actually getting those assigned variables, but I'm completely lost on the best approach to achieve my goal-
The main intent of "don't do work in your constructor" is to avoid side effects where you create an object and it does a significant amount of work that can impact global state unexpectedly or even take a long time to complete which may disrupt the caller's code flow.
In your case, you're just setting up parameter values, so this is not the intention of "don't do work", since this isn't really work. The design of your final container depends on your requirements - if you can accept a variable list of properties that are set on your class (or struct) then perhaps an initializer when you construct the object is more appropriate.
Assuming that you want all of your properties from the get go, and that you want grouping like you called out in the question, I would construct something similar to:
public class Properties
{
public ServerProperties Server { get; private set; }
public CustomerProperties Customer { get; private set; }
public Properties(ServerProperties server, CustomerProperties customer)
{
Server = server;
Customer = customer;
}
}
I'm leaving the implementation of ServerProperties and CustomerProperties to you, but they follow the same implementation pattern.
This is of course a matter of preferences but I always give my constructors all the parameters they need so that my objects has basic functionality. I don't think that 5 parameters is bloated and adding a container to pass parameters adds much more bloat in my opinion than adding a few more parameters. By new bloat I mean that you will probably have a new file for that, with new classes and new imports. Calling code has to write more using directives and link to correct libraries which needs to be exported correctly as well.
Adding a wrapping class for parameter masks the real problem, that your class might be too complicated, it does not solve it and generally aggravates it.
You can have any amount of parameters you want in a constructor. It's just that if you have too many (how many is too much? that's really subjective), it gets harder and harder to make a new instance of that class.
For example, suppose you have a class with 30 members. 27 of them can be null. If you force it to receive a value for each member in the constructor, you'll get code like this:
Foo bar = new Foo(p1, p2, p3, null, null, null, null, null, null /*...snip*/);
Which is boring to write and not very readable, where a three parameter constructor would do.
IMO, this is what you should receive in your constructors:
First, anything that your instance absolutely needs in order to work. Stuff that it needs to make sense. For example, database connection related classes might need connection strings.
After those mentioned above, you may have overloads that receive the stuff that can be most useful. But don't exagerate here.
Everything else, you let whomever is using your code set later, through the set accessor, in properties.
Seems to me like you could use dependency injection container like Unity or Castle Windsor.

How to fix 'microsoft.maintainability' build error?

I have a controller which contains a few private read only interface properties which it needs in order to get data by calling a service which is then used to populate models etc
private readonly ISomeInterface _someObject;
Which gets set in the Controllers constructor:
public ... (ISomeInterface someInterface, ...) {
...
_someObject = someObject
}
_someObject is then used in a call to the service layer to get data.
I had to add another property to the controller but now when I build the soloution I get the following error:
CA1506 : Microsoft.Maintainability : 'ControllerName' is coupled with 87 different types from 30 different namespaces. Rewrite or refactor this class's methods to decrease its class coupling, or consider moving some of the class's methods to some of the other types it is tightly coupled with.
It asks me to reduce the coupling of the class, I understand that one way of doing this is to code against interfaces (abstractions) - which I'm already doing by adding the interface property? It seems by adding one more property it takes it past the threshold for flagging up this error.
If I remove it, I can't get the data I need? What do I need to modify?
How many actions does your controller have? Do you have a view model for each action? Do you have an input model for each action? Are you interacting with different classes for each controller action? You may need to split your controller up into multiple controllers to make it do less giving it fewer reasons to change and also fewer dependencies. Although using an interface would decouple the controller from the specific implementation of ISomeInterface it doesn't do anything in terms of that warning. Changing to using the Interface didn't reduce the number of types... it just changed from concrete type to an interface type.
The problem is warning against having one class that does many many things. Having many dependencies suggests the class is doing too much and should be divided up. For example if this controller has say an action for "Bake Pie" and "Eat Pie" and "Make Ice Cream" and "Deliver food" you could move "deliver food" to a brand new class... you could break out the Make Ice Cream as well and then you would evaluate if Bake Pie and Eat Pie should stay together in the same class or be put in separate classes. The pies debate opens a can of worms which folks would debate.
see: SOLID (object-oriented design)
Do you have code that has to call 2 or more different data access classes that then calls another class to to create a view model. You could move that whole operation to a new class thus reducing your dependency on 3 classes down to 1.

Dependency Injection Optional Parameters

Is it considered a bad practice to use optional parameters when using dependency injection frameworks with Constructor injection?
Example:
public class ProductsController
{
public ProductsController(IProductService productService = null, IBackOrderService = null)
{
}
}
I have specified both parameters as optional, but my DI framework will always inject both dependencies. If I add a new action to my controller which requires a new dependency, would it be bad to make the new dependency optional? I could potentially be breaking dozens of unit tests even though the existing tests wouldn't require the new dependency.
Edit
People seem to be confused by my question. I am never construcing a ProductsController manually in my web application. This is handled by a controller factory (which automatically injects dependencies).
What I don't like is having a unit test like this:
[Test]
public void Test1()
{
var controller = new ProductsController(new MockProductService(), new MockBackOrderService());
}
Now I decide to add a new action method to my controller. This new action needs a new dependency but none of the existing actions do. Now I have to go back and modify 100 different unit tests because I added a new parameter. I can avoid that by making the parameters optional, but I wanted to know if it was a bad idea. My gut feeling says no because the only thing it affects are the unit tests.
I completely agree with the accepted answer for all the cases on that defining a Dependency means that implementation will not work with out it.
But what if you have something that does not necessarily need a dependency but you want to be able to configure something if that dependency has been loaded. OK...? that sounds a bit weird but its a valid Meta Programming use case - and you think maybe factory pattern could help.. but even the factory may need some, none or all dependencies so Factory does not solve this problem.
Real world problem of feature flags. If a feature is turned off you
don't need that dependency.. or maybe cant even create it because
there is no concrete implementation. So its turned off. It compiles,
everything works OK. But then somebody switches the feature on and all
of a sudden we need that dependency.
I found a way to do this -- and the best part is I only realised how to do this by learning about another not so well known technique with Dependency Injection (I am using Microsoft.Extensions.DependencyInjection)
Injecting several concrete implementations for a single Interface
services.AddTransient<IWarehouseRepo, ActionRepository>();
services.AddTransient<IWarehouseRepo, EventRepository>();
services.AddTransient<IWarehouseRepo, AuditRepository>();
services.AddTransient<IWarehouseRepo, ProRepository>();
services.AddTransient<IWarehouseRepo, SuperWarehouseRepository>();
services.AddTransient<IWarehouseRepo, InferiorWarehouseRepository>();
services.AddTransient<IWarehouseRepo, MonthlyStatisticsRepository>();
I only learnt recently that this is completely valid but for this to work your constructor needs to look like this..
public WarehouseHandler(IEnumerable<IWarehouseRepo> repos)
So that is super cool! I can select a repository I need based on whatever criteria. But how does this help with Optional Dependencies?
Because this type of constructor will give you 0 or more dependencies. So if you do not add any dependencies you can branch out in the constructor using a conditional statement
if (repos.Count() == 0)
return;
This is null reference safe, does not require default values, easy to debug, easy to read and easy to implement.
You can now also use this technique as the feature switch mechanism too!
I don't think it's a good idea. Constructor injection means that the dependencies are required. You should even add the guard lines that throws if one of the parameters is null.
I think the problem is with your unit tests. For instance I have only one place where the controller is created and supporting objects are mocked (controllerContext, HttpContext, Request, Response, etc.). Then if I add a new parameter in the constructor I have to change it only in one place in the unit tests.
Maybe you should consider to code a generic base class in your unit tests, or make a usage of "setup" routine for the tests.
Consider to use The Test Data Builder pattern.
In the simplest form it could be done as static test helper method
public ProductsController BuildControllerWIthMockDependencies ()
{
var controller = new ProductsController(new MockProductService(), new MockBackOrderService());
return controller;
}
You can use AutoFixture as a generic Test Data Builder.
Further techniques for using Test Data Builders can be found in Test Data Builders: an alternative to the Object Mother pattern

Factory object causes stackoverflowexception due to dependancy upon itself

I have a c# factory object which creates objects through factory methods, using a list of objects as a source.
The list of objects is created like this:
public WidgetFactory()
{
widgetLibrary = new List<WidgetModel>();
//Add all widgets
widgetLibrary.Add(new ClientsWidget());
widgetLibrary.Add(new InstallationsWidget());
etc.
and various parts of my application access this list in different ways to get the type of object it needs.
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
Typically, objects should not rely on the factory that creates them for construction, as it causes exactly this problem. If you can push in the reference to the factory, but not use it until it's needed, it may solve the issue.
If you absolutely need to do this, then the best approach may be to lazily instantiate the objects within the factory. Instead of having your WidgetFactory contain a List<WidgetModel> internally, you could use a List<Lazy<WidgetModel>>. This would allow the individual "widgets" to only evaluate as needed, which would mean that, when the widget in question tries to reference the factory, it'll be fully loaded.
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
Your model is wrong. Once a car has left the assembly line at the NUMMI plant, it doesn't depend on the plant to operate properly.
Also, I question the design of your factory. Why are you new instances the constructor. What purpose is that serving?
You should probably tell us a little bit more about your model and why you think you need this. Odds are, properly done, you don't.
The constructor for the WidgetFactory should not be calling the constructers of the things that it is building. Instead, the WidgetFactory should have a method (BuildWidgets) that does all of the work.
Then the other objects can make some use of the factory without causing this cascade of activity to start over again.
For starters, move Widget creation out of the WidgetFactory's constructor. This should happen either in an initialization method or on-demand in a CreateWidget(Type) method.
To make the factory instance available to the Widget instances, you can do one of a few different things:
Have WidgetFactory pass 'this' when it creates the Widget
Use the singleton pattern: add a static property WidgetFactory.Instance and initialize it once; have all WidgetFactory users access the property rather than create a new instance.
Use the dependency injection pattern -- difficult to provide a short description here.

Categories

Resources