Dependency injection through constructor or attribute? [duplicate] - c#

I'm refactoring a class and adding a new dependency to it. The class is currently taking its existing dependencies in the constructor. So for consistency, I add the parameter to the constructor.
Of course, there are a few subclasses plus even more for unit tests, so now I am playing the game of going around altering all the constructors to match, and it's taking ages.
It makes me think that using properties with setters is a better way of getting dependencies. I don't think injected dependencies should be part of the interface to constructing an instance of a class. You add a dependency and now all your users (subclasses and anyone instantiating you directly) suddenly know about it. That feels like a break of encapsulation.
This doesn't seem to be the pattern with the existing code here, so I am looking to find out what the general consensus is, pros and cons of constructors versus properties. Is using property setters better?

Well, it depends :-).
If the class cannot do its job without the dependency, then add it to the constructor. The class needs the new dependency, so you want your change to break things. Also, creating a class that is not fully initialized ("two-step construction") is an anti-pattern (IMHO).
If the class can work without the dependency, a setter is fine.

The users of a class are supposed to know about the dependencies of a given class. If I had a class that, for example, connected to a database, and didn't provide a means to inject a persistence layer dependency, a user would never know that a connection to the database would have to be available. However, if I alter the constructor I let the users know that there is a dependency on the persistence layer.
Also, to prevent yourself from having to alter every use of the old constructor, simply apply constructor chaining as a temporary bridge between the old and new constructor.
public class ClassExample
{
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo)
: this (dependnecyOne, dependencyTwo, new DependnecyThreeConcreteImpl())
{ }
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo, IDependencyThree dependencyThree)
{
// Set the properties here.
}
}
One of the points of dependency injection is to reveal what dependencies the class has. If the class has too many dependencies, then it may be time for some refactoring to take place: Does every method of the class use all the dependencies? If not, then that's a good starting point to see where the class could be split up.

Of course, putting on the constructor means that you can validate all at once. If you assign things into read-only fields then you have some guarantees about your object's dependencies right from construction time.
It is a real pain adding new dependencies, but at least this way the compiler keeps complaining until it's correct. Which is a good thing, I think.

If you have large number of optional dependencies (which is already a smell) then probably setter injection is the way to go. Constructor injection better reveals your dependencies though.

The general preferred approach is to use constructor injection as much as possible.
Constructor injection exactly states what are the required dependencies for the object to function properly - nothing is more annoying than newing up an object and having it crashing when calling a method on it because some dependency is not set. The object returned by a constructor should be in a working state.
Try to have only one constructor, it keeps the design simple and avoids ambiguity (if not for humans, for the DI container).
You can use property injection when you have what Mark Seemann calls a local default in his book "Dependency Injection in .NET": the dependency is optional because you can provide a fine working implementation but want to allow the caller to specify a different one if needed.
(Former answer below)
I think that constructor injection are better if the injection is mandatory. If this adds too many constructors, consider using factories instead of constructors.
The setter injection is nice if the injection is optional, or if you want to change it halfway trough. I generally don't like setters, but it's a matter of taste.

It's largely a matter of personal taste.
Personally I tend to prefer the setter injection, because I believe it gives you more flexibility in the way that you can substitute implementations at runtime.
Furthermore, constructors with a lot of arguments are not clean in my opinion, and the arguments provided in a constructor should be limited to non-optional arguments.
As long as the classes interface (API) is clear in what it needs to perform its task,
you're good.

I prefer constructor injection because it helps "enforce" a class's dependency requirements. If it's in the c'tor, a consumer has to set the objects to get the app to compile. If you use setter injection they may not know they have a problem until run time - and depending on the object, it might be late in run time.
I still use setter injection from time to time when the injected object maybe needs a bunch of work itself, like initialization.

I personally prefer the Extract and Override "pattern" over injecting dependencies in the constructor, largely for the reason outlined in your question. You can set the properties as virtual and then override the implementation in a derived testable class.

I perfer constructor injection, because this seems most logical. Its like saying my class requires these dependencies to do its job. If its an optional dependency then properties seem reasonable.
I also use property injection for setting things that the container does not have a references to such as an ASP.NET View on a presenter created using the container.
I dont think it breaks encapsulation. The inner workings should remain internal and the dependencies deal with a different concern.

One option that might be worth considering is composing complex multiple-dependencies out of simple single dependencies. That is, define extra classes for compound dependencies. This makes things a little easier WRT constructor injection - fewer parameters per call - while still maintaining the must-supply-all-dependencies-to-instantiate thing.
Of course it makes most sense if there's some kind of logical grouping of dependencies, so the compound is more than an arbitrary aggregate, and it makes most sense if there are multiple dependents for a single compound dependency - but the parameter block "pattern" has been around for a long time, and most of those that I've seen have been pretty arbitrary.
Personally, though, I'm more a fan of using methods/property-setters to specify dependencies, options etc. The call names help describe what is going on. It's a good idea to provide example this-is-how-to-set-it-up snippets, though, and make sure the dependent class does enough error checks. You might want to use a finite state model for the setup.

I recently ran into a situation where I had multiple dependencies in a class, but only one of the dependencies was necessarily going to change in each implementation. Since the data access and error logging dependencies would likely only be changed for testing purposes, I added optional parameters for those dependencies and provided default implementations of those dependencies in my constructor code. In this way, the class maintains its default behavior unless overridden by the consumer of the class.
Using optional parameters can only be accomplished in frameworks that support them, such as .NET 4 (for both C# and VB.NET, though VB.NET has always had them). Of course, you can accomplish similar functionality by simply using a property that can be reassigned by the consumer of your class, but you don't get the advantage of immutability provided by having a private interface object assigned to a parameter of the constructor.
All of this being said, if you are introducing a new dependency that must be provided by every consumer, you're going to have to refactor your constructor and all code that consumers your class. My suggestions above really only apply if you have the luxury of being able to provide a default implementation for all of your current code but still provide the ability to override the default implementation if necessary.

Constructor injection does explicitly reveal the dependencies, making code more readable and less prone to unhandled run-time errors if arguments are checked in the constructor, but it really does come down to personal opinion, and the more you use DI the more you'll tend to sway back and forth one way or the other depending on the project. I personally have issues with code smells like constructors with a long list of arguments, and I feel that the consumer of an object should know the dependencies in order to use the object anyway, so this makes a case for using property injection. I don't like the implicit nature of property injection, but I find it more elegant, resulting in cleaner-looking code. But on the other hand, constructor injection does offer a higher degree of encapsulation, and in my experience I try to avoid default constructors, as they can have an ill effect on the integrity of the encapsulated data if one is not careful.
Choose injection by constructor or by property wisely based on your specific scenario. And don't feel that you have to use DI just because it seems necessary and it will prevent bad design and code smells. Sometimes it's not worth the effort to use a pattern if the effort and complexity outweighs the benefit. Keep it simple.

This is an old post, but if it is needed in future maybe this is of any use:
https://github.com/omegamit6zeichen/prinject
I had a similar idea and came up with this framework. It is probably far from complete, but it is an idea of a framework focusing on property injection

It depends on how you want to implement.
I prefer constructor injection wherever I feel the values that go in to the implementation doesnt change often. Eg: If the compnay stragtegy is go with oracle server, I will configure my datsource values for a bean achiveing connections via constructor injection.
Else, if my app is a product and chances it can connect to any db of the customer , I would implement such db configuration and multi brand implementation through setter injection. I have just taken an example but there are better ways of implementing the scenarios I mentioned above.

When to use Constructor injection?
When we want to make sure that the Object is created with all of its dependencies and to ensure that required dependencies are not null.
When to use Setter injection?
When we are working with optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency.
Additionally, setter methods make objects of that class open to reconfiguration or re-injection at a later time.
Sources:
Spring documentation ,
Java Revisited

Related

Unity Container: Difference between constructor vs property vs method injection

This is specific to Unity DI.
It seems common wisdom states that if the majority of your class requires a certain dependency then you should use constructor injection. If the dependency is only needed in a subset of use cases for the class then you should use property injection (or possibly method injection). I assumed this was because the latter two don't resolve the object until they're referenced, but in my experience all three of these resolve the dependencies on object creation, so what is the utility of using one over the other?
Also, the Unity documentation on deferring object creation only mentions the Lazy<> and Func<> generics.
Is there a way to set up property and/or method injection to defer resolution?
If not, are there different methods just to allow for stylistic preferences?
Ok, basically deferring resolution using properties is a bad practice. Some DI containers (Microsoft.Extensions.* https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1) does not even allow you to do that.
If your code followed SOLID principles (https://en.wikipedia.org/wiki/SOLID), the need to defer resolution would almost never occur. Instead, you should split your classes into smaller pieces and each would inject through its constructor. If you still need to defer the resolution (e.g., when you create a facade), you can inject an abstract factory and called its factory method to instantiate instance when you need it.

What are the benefits of using Dependency Injection when retrieving implementations of an interface at runtime?

public List<IBusinessObject> RetrieveAllBusinessObjects()
{
var businessObjectType= typeof(IBusinessObject);
List<Type> implementationsOfBusinessObject = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(businessObjectType.IsAssignableFrom).ToList();
return implementationsOfBusinessObject.Select(t =>(IBusinessObject)Activator.CreateInstance(t)).ToList();
}
I was suggested by a user on stack overflow that I should check out dependency injection as a workaround for the above snippit. What would be the benefits of this?
Just a little overview on what the scenario is:
Our database has little to no store procedures so we have begun implementing C# business objects for our more complicated tables. As we are hoping to switch databases some time soon this seems to be the best option. All of the business objects must be loaded using reflection at runtime to help manage them. All of these business objects implement the interface IBusinessObject.
The suggestion to use dependency injection came from this question
EDIT:
The RetrieveAllBusinessObjects method is in a class behind an interface so is directly testable
We use AutoFac if that changes anything. We don't use a separate config file.
-
instead of using the code above, you simply use DI which is configured in the config file of the app but also sometimes you can decorate a property or a parameter in a method which will then be automatically injected in (by the mapping set up either programmatically or via config) when the request is made to access that object or when it is going to be invoked in the method being called in the params.
it also makes it a bit more testable in that you can create different concrete types which implement of an interface, then instead of having to recompile the code, you just flick the mappings by the config file and viola...all works.
DI would do the above without you having to write code to do it so there's less opportunity for you to introduce bugs.
DI gives you many more benefits such as
Making it easier to test individual units of code. Dependencies can be mocked, so you can limit the code being tested
Easy to understand the dependencies within your code. Dependencies generally get injected in certain places, usually the constructor.
Linked to 1/ above, because you should now defined interfaces between your code, when your requirements change & you need to rewrite a component, you can do so with a higher level confidence that it will work with your existing code-base.
There are other benefits that others can probably describe better, but you'll need to evaluate those according to your needs.

Busy constructors in Ioc - are they a code smell?

I have ended up with a constructor that looks like this whilst attempting to end up with an object i can easily test.
public UserProvider(
IFactory<IContainer> containerFactory,
IRepositoryFactory<IUserRepository> userRepositoryFactory,
IFactory<IRoleProvider> roleProviderFactory,
IFactory<IAuthenticationProvider> authenticationProviderFactory,
IFactory<IEmailAdapter> emailAdapterFactory,
IFactory<IGuidAdapter> guidAdapterFactory,
IRepositoryFactory<IVehicleRepository> vehicleRepositoryFactory,
IRepositoryFactory<IUserVehicleRepository> userVehicleRepositoryFactory,
IFactory<IDateTimeAdapter> dateTimeAdapterFactory)
This is all the dependencies the object will have and is the busiest constructor i have. But if someone saw this would it really raise a big wtf?
My aim was to end up with logic that is easy to test. Whilst it requires a good amount of mocks it is certainly very easy to verify my logic. However i am concerned that I may of ended up with too much of a good thing.
I am curious if this is normal for most people implementing ioc.
There are several simplifications I can make - such as I don't really need to pass in the factories for several of the adapters as i could just pass the adapter in directly as it has no internal state. But I am really asking in terms of the number of parameters.
Or more to the point i am looking for assurance that I am not going overboard ;)
But I am beginnign to get the impression that the UserProvider class should be broken down a bit - but then I end up with even more plumbing which is what is driving this concern.
I guess a sub question is maybe should I be considering using a service Locator pattern if I have these concerns?
When using DI and constructor injection violation of the SRP becomes very visible. This is acutally a good thing, and it is not DI / IOC's fault. If you were not using constructor injection, the class would have the same dependencies, it would just not be as visible.
What you could do in your concrete example is hide some of the related dependencies behind facades. For example IVehicleRepository and IUserVehicleRepository could be hidden behind an IVehicle facade. It might also make sense to put IUserRepository, IRoleProvider and IAuthenticationProvider behind a facade.
In my opinion that is a lot of parameters for a constructor. Here's how I would handle this to get good testability and reduce "code smell."
Instead of passing in the factories to create instances of your classes just pass in the classes themselves. This automatically cuts your dependencies in half because the UserProvider would not be concerned with creating any objects that it needs (and subsequently disposing of them if necessary) it would just use what is given to it instead of using the factories that it needs to create object instances that it needs.
Remove your adapters from the constructor and just create instances of these interfaces inside of the UserProvider. Think about how often are you going to need to change the way you format a guid for example. This would still be testable as long as your adapters don't have a lot of dependencies.
The point I'm making is to get a good balance of testability and practicality. When implementing Ioc try and determine where you've had trouble with testability in the past and where you've had issues maintaining and changing code because there were too many dependencies. That is where you'll see the most benefit.

Passing constructor parameters when resolving types in Unity: Best practice

It's sometimes necessary when using dependency injection to provide the parameters to use in the constructor. This is something that's supported in Unity (and other dependency injection containers), so that when it tries to create an instance of the type, it can provide your arguments as parameters in the constructor.
My question is: is this approach desirable?
Within an interface it is not possible to specify which parameters an implementing class must have. By specifying the parameters to Unity, you are assuming that the implementing class has these parameters, and you are placing implicit constraints over future implementing classes. These constraints cannot be communicated through the interface.
So, is this is flaw in how interfaces themselves are specified (in .NET), eg. should it be possible to specify constructor signatures? Or has this feature (of being able to provide constructor parameters) been included in Unity due to some other need?
The only real workable approach (to me) seems to be use a factory to create the implementing classes, and do dependency injection on the factory.
I appreciate my question here might not be clear, so I'll ask it slightly differently: what's the best way to do dependency injection on a class which has a constructor requiring parameters?
(I do not believe this question to be subjective, as there should probably be a single design pattern for this type of dependency injection.)
EDIT:
I should add, that my main problem is that I may create a new implementing class which has additional constructor parameters (where the constructor parameters are not things that can be created by unity).
I'm not sure where you got the idea that constructor injection does not fit with DI. I'd say that the real situation is the opposite of that: constructor injection is one of the most common patterns utilised to achieve dependency injection - I'd go as far as saying that it is the most common pattern, and that view is certainly backed up by the fact that that majority of Inversion of Control containers (DI containers) use constructor injection as their preferred mechanism.
StructureMap for example has a core, very specific support for constructor injection where it will pick the constructor with the most parameters as the constructor used for dependency resolution.
What you are saying by using the constructor injection pattern is that "I am removing the hard coded dependencies within my class by specifying them as parameters passed into the constructor - my class cannot be instantiated without these dependencies". Of course, the first half of that statement is the essence of DI, but the second half enforces this more.
Dependencies are an implementation detail that should be able to be changed easily, providing a flexible, loosely coupled solution. They are about the how, not the what. Interfaces specify the what. So I'd say that your suggestion of specifying dependencies in interfaces actually goes against the concept of dependency injection.
And as far as your statement about factories - this is exactly what IOC containers are - great big factories that take care of a solution's dependency tree, so you don't need to care.
Edit
I think maybe you are asking about the case where you want to provide a non-dependency constructor parameter, such as an id for a referenced entity, or an initial state enum?
I personally don't see a problem with an IOC container allowing for this. It is still initial state of your class and hence the rules for the creation of that state need to be explicitly expressed. It can mean that you sometimes need more references to your IOC container that you might like, but it is not a horrible enough situation to abandon the other benefits of counstructor injection.
The responsibility of IoC containers (say Unity) is to connect interfaces with concrete implementations. That means your container must know the interface and how to create the object that implements the interface. Using constructor injection is perfectly legal and the recommended way. Unity will create the concrete implementation when your application requests an interface through the Resolve() method.
The Unity container itself is the factory that creates your objects, you use Unity because you don't want to implement those factories by yourself.
The issue here is the definition of the InjectionConstructor in Unity vs say the one in Castle.Windsor.
In Unity, if you need to inject a particular parameter, say an AppSetting you are also forced to supply all the other parameters thus fixing the signature of the constructor. However, in Castle.Windsor it takes the parameter you've supplied and then uses the resolution mechanism to locate the other paramaters in the normal way.
It would be possible to introduce this into Unity by writing a custom Builder strategy that did a "best-fit" approach to which constructor to use rather than the default greedy/supply everything which is the default.

Pattern for objects initialization at startup

I'm building an application and as time goes on, I have more and more objects to initialize at startup. Moveover, some of the newer objects depend on others so I'm getting some kind of spaggetti initialization where objects are created then passed to other constructors. I'm suspecting that I'm getting it wrong.
For example I have a WinForm which accepts a "Controller" class and 2 events. The controller needs to be told about the existence of a DataGridView from the WinForm so it has a method
Controller::SetDataGridReference(DataGridView^ dgv)
Is there a general method of instanciating objects at startup then referencing those objects to each another?
I've been told that putting all the required classes as constructor parameters is a good practice but frankly, I don't see how I can do that here.
I don't really think that the language matters
This looks like a textbook case for using dependency injection (DI). It will certainly help with your spaghetti code and can even assist with unit testing. If you want to make a gradual migration towards DI you might want to consider refactoring the objects with similar relationships and using a few sets of factory classes that can handle all the boilerplate chain intialization as well as centralizing where all that takes place in your code base.
I can recommend Google Guice as a good DI framework for Java. Even if you arent using Java it is a good DI model to compare against other language's DI frameworks
Two patterns pop into mind as possibly appropriate depending on the specifics of your problem:
Abstract Factory Pattern. This can work with or without the Dependency Injection approach suggested by #Scanningcrew.
Mediator Pattern. Construct a mediator. Pass the mediator into the constructor of each object. Have each object register with the mediator. Then the objects don't need to know about each other explicitly. This works well when you have a set number of objects interacting with each other.
Use the Controller Design Pattern.
That is, create a SINGLE class that will be instanced on program initialization, called Controller. On the constructor of that class, create all other objects. Whatever object that needs any other objects should receive said object as a parameter on its constructor. No one, no absolutely any other object should create anything on their constructor. Pass everything as parameters on their constructors. Also, on the Controller class destructor/dispose call all objects destructor/dispose method in reverse order. This won't reduce your code, but it will make if far better to understand and debug later on.
Dependency Injection should help here: at application boot you can choice to build the complete (or sort of) graph of objects. The entry point of your application will instantiate the DI container of your choice, the you just request the root object.
For example Google Guice comes with a very nice Object grapher.
For the objects interaction, I would go for a Mediator. Check out this definition:
"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
For the instantiation, I would consider the Dependency Injection. Remember that you can freely use and mix design patterns to achieve your goals.

Categories

Resources