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
Normally I'd just use a singleton pattern for the model class Logbook. However, I'm trying to move towards learning about DI and want to inject the model into my viewmodel. In addition, I'm planning on having different child windows that open for various function (choose which logbook entries to display, sort order, add a logbook entry, etc) that may or may not need access to the model. What are the pros and cons of using the singleton pattern vs DI with these constraints? In addition, is DI possible if a lot of my viewmodels need access to this model? Finally, where/how should I instantiate the view, viewmodel, and model to be able to inject?
When you're using dependency injection, the idea is to provide classes with a specific implementation of the dependency it needs, so when you're unit testing, you can provide a mock or stub implementation. This is known as loose coupling.
Singletons, meanwhile, are global state that you have no control over. If your class accesses a singleton, it's tightly coupled to the singleton. How do you mock a singleton? In general, you don't. You're stuck to it, and suddenly you have untestable code. Singletons are generally considered an anti-pattern for exactly this reason. (Aside: there are ways around that, but the basic design problem still exists)
Even worse, if something in your class mutates the state of the singleton, this can have side effects in other tests you're writing and make it very difficult to figure out why Test B passes when run alone, but fails if it's run after Test A.
My rule of thumb is Don't use singletons, ever.
Your specific question sounds a little bit fishy. Your viewmodel shouldn't need a model injected into it. It sounds like you want a class responsible for retrieving or otherwise constructing your model, and then you'd inject an implementation of that class into your viewmodel.
I am trying to get rid off static classes, static helper methods and singleton classes in my code base. Currently, they are pretty much spread over the whole code, especially so for the utility classes and the logging library. This is mainly due to the need for mocking ability as well as object-oriented design and development concerns, e.g. extensibility. I might also need to introduce some form of dependency injection in the future and would like to leave an open door for that.
Basically, the problem I have encountered is about the method of passing the commonly used references around. These are objects that are used by almost every class in the code base, such as the logging interface, the utility (helper) class interface and maybe an instance of a class that holds an internal common state for the assembly which most classes relate to.
There are two options, as far as I'm aware. One is to define a class (or an interface) that stores the common references, a context if you will, and pass the context to each object that is created. The other option is to pass each common reference to almost every class as a separate parameter which would increase the number of parameters of the class constructors.
Which one of these methods is better, what are the pros and cons of each, and is there a better method for this task?
I generally go with the context object approach, and pass the context object either to an object's constructor, or to a method -- depending on which one makes the most sense.
The context object pattern can take a few forms.
You can define an interface that has exactly the members you need, or you can generate a sort of container class. For example, when writing loosely-coupled components, I tend to have each component I implement have a matching interface, so that it can be reimplemented if desired. Then I register the objects on a "manager" object, something like this:
public interface IServiceManager
{
public T GetService<T>();
public T RequireService<T>();
public void RegisterService<T>(T service);
public void UnregisterService<T>(T service);
}
Behind the scenes there is a map from type to object, which allows me to extremely quickly assemble a large set of diverse components into a working whole. Each component asks for the others by interface, and the manager object is what glues them together. (If you correctly author your components, you can even swap out one service for another while the process is running!)
One would register a service something along these lines:
class FooService : IFooService { }
// During process start-up:
serviceManager.RegisterService<IFooService>(new FooService());
There is more overhead with this approach than with the flat-interface approach due to the dictionary lookup, but it has allowed me to build very sophisticated systems that can be easily redeployed with different service implementations. (And, as is usual, any bottlenecks I encounter are never in looking up a service object from a dictionary, but somewhere else such as the database.)
You're going to get varied opinions, but generally passing a separate parameter to the constructor for each dependency is preferred for a few reasons:
It clearly defines the actual dependencies for a class - with a "context" you don't know which parts of the context are used without digging into the code.
Generally having a lot of parameters to a constructor is a design smell, so using constructor injection helps you sniff out design flaws.
When testing you can mock out individual dependencies versus having to mock an entire context
I would suggest passing as a parameter to the constructor. This has great advantage for both dependency injection and unit testability ( mocking).
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.
More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.