When to use property injection? - dependency-injection

When should I use property injection?
Should I use by default constructor injection if instance creation in fully controlled?
Am I right that using a constructor injection I write container-agnostic code?

When should I use property injection?
You should use property injection in case the dependency is truly optional, when you have a Local Default, or when your object graph contains a cyclic dependency.
Property Injection however causes Temporal Coupling and when writing Line of Business applications, your dependencies should never be optional: you should instead apply the Null Object pattern.
Neither should you use a Local Default, which is:
"A default implementation of an abstraction that's defined in the same assembly as the consumer." [DIPP&P, Section 4.2.2]
Local Defaults should not be used in Line of Business applications, because it complicates testing, hides the dependency, and makes it easy to forget to configure the dependency.
Neither should object graphs have cyclic dependencies. This is an indication of a problem in your application design.
Should I use by default constructor injection if instance creation in fully controlled?
Yes. Constructor injection is the best way. It makes it very easy to see which dependencies a class has, makes it possible to make dependencies required, and prevents Temporal Coupling.
Am I right that using a constructor injection I write container-agnostic code?
This is correct. Constructor injection allows you to delay the decision of which DI library to use, and whether at all you use a DI library.
For a more detailed explanation of the above, and much more, read the book Dependency Injection Principles, Practices, and Pattern (DIPP&P) by Mark Seemann and myself.
The usefulness of property injection is so limited, that while working on the book, Mark and I even discussed labeling Property Injection an anti-pattern. In the end we felt we couldn't make a case that was as strong as, for instance, Ambient Context, which we did decide to describe as an anti-pattern in that edition. The case for Ambient Context was crystal clear, while being much muddier for Property Injection. But this is why, however, we added many warning notes to the Property Injection section (4.4), because we feel strongly Property Injection is not a good solution for the majority of cases.
There are several problems, though, that Property Injection seems to solve at first, such as the problem of Constructor Over-Injection (where a constructor contains many dependencies). Constructor Over-Injection, however, is almost always caused by design deficits, such as:
Class having too many responsibilities
Lack of natural clusters
Choosing inheritance over composition
Application of Cross-Cutting Concerns through base classes instead of Decorators or Interceptors

The accepted answer argues in favor of constructor injection and takes a rather critical stance toward property injection. As such, it does not put focus on addressing the problems that property injection actually solves, if used correctly. Therefore I want to take the opportunity to address some of these points and also to provide some counter arguments to the accepted answer.
When should I use property injection?
Imagine you have a project with 100+ controllers and all those controllers are extending a custom base controller (parent-service). In such a situation, where a service is extended by several child-services, employing constructor injection is a burden: For every constructor you create, you need to relay arguments to your parent-service's constructor. If you decide to extend your parent service's constructor signature you will also be forced to extend the signatures of all child-services' constructors.
To make this example more vivid, say you start your project with a base controller having a parameterless constructor.
Now after a month you decide you want a logger service in your base controller. → Not only will you have to change the base controller constructor's signature but also those of your 100+ child controllers.
Now again after a month you need access to a user service in your base controller → Again, you'll have to change the constructor signature of your 100+ child controllers.
you get the point...
With property injection you can easily circumvent this whole inconvenience by simply adding the necessary properties to your parent service and letting your DI-mechanism handle the injection via reflection. As a side effect, this also greatly reduces the risk of merge conflicts (since the files touched is reduced to a minimum).
So far, I have been talking mostly about controllers but this example counts for any situation in which you have a service hierarchy – the deeper or broader this hierarchy gets, the greater the burden of constructor injection. However, avoiding service-hierarchies altogether may not always be a reasonable choice in a project.
One could say the decision between property and constructor injection is really a decision between a pragmatism and OOP "purism".
From a "purist" OOP perspective, the rule is (as stated in the accepted answer) to initialize all required fields of a class via its constructor in order to avoid granting any access to the newly created instance in an "unfinished" state (which may result in an exception being later thrown).
With reference to this rule, an OOP-purist has a valid point in saying that property injection (temporarily) leaves your services in an "unfinished" state (the timespan between when your constructor has returned and the moment your property is injected) and that this increases the risk that your application may break.
However, when talking about services managed by an IoC/DI container, this risk is practically reduced to zero if you consider that your DI-mechanism is responsible for resolving the dependency graph and wiring everything up before any user-action or api-request actually makes it into your system or needs being processed. For example, at the time a controller's action is invoked you can be sure that your services were properly wired up and injected into your controller's properties (given of course, that you configured them correctly in advance).
Also the argument that it is only possible with constructor injection to make your dependencies "required" is rather weak in a world where you are not responsible for manually injecting services into your classes but delegate this task to your IoC mechanism. Even worse, you may get a false sense of security because you stated via constructor that a ServiceX requires ServiceY – but if you forgot to register your ServiceY with your DI-mechanism, you merely get null injected into your ServiceX's constructor.
Another "argument" against property injection is that it becomes harder for your fellow programmers to distinguish between properties that are managed by the DI mechanism and those which are simply non-DI-related. However, in this case you can just use a marker attribute to "opt-in" for DI or add short comments above your properties to clear things up, when the case is not clear. Also, in a service-class, it is rather unusual to have properties referring to other services that are not supposed to be manged by your DI mechanism.
Finally, as for saying that constructor injection makes unit testing easier (since you know what dependencies are required by a class), I would simply argue, that with property injection you will soon enough notice that you forgot to include a dependency when your tests begin to fail due to a certain service being undefined.
Should I use by default constructor injection if instance creation in fully controlled?
With all the above being said, I think I can answer your second question with: Not necessarily.
It depends on your project's size, the kind of service-hierarchy you employ, how often your parent-services' dependencies change and how much time and resources you are willing to invest in managing parameters and passing arguments up the service-hierarchy.
Am I right that using a constructor injection I write container-agnostic code?
Yes! – Under the premise that you are not injecting the container itself... which you shouldn't! ;)
All the above being said, here are some quotes from Martin Fowler's great discussion on dependency injection directly addressing the question of constructor vs setter/property injection, and I can fully subscribe to the last quote :)
If you have multiple constructors and inheritance, then things can get particularly awkward. In order to initialize everything you have to provide constructors to forward to each superclass constructor, while also adding you own arguments. This can lead to an even bigger explosion of constructors.
Despite the disadvantages my preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I've outlined above start to become a problem.
This issue has led to a lot of debate between the various teams who provide dependency injectors as part of their frameworks. However it seems that most people who build these frameworks have realized that it's important to support both mechanisms, even if there's a preference for one of them.
A final remark: If you, for some reason, want to switch back from property injection to constructor injection, no problem, you can always add a constructor with the parameters to be injected and assign the properties via your constructor – dead-simple.

Related

Concrete class injection considered bad practice

I am curious about dependency inversion principle in general, and whether it should be enforced strictly all the time.
I know that using interfaces to be injected in general promotes loose coupling, which has positive impact.
However, there are certain types of class that will most likely always have only one implementation, and likely not to change over time. I really am questioning having every objects backed by an interface, e.g. FooService, with FooServiceImpl.
I am in a dilemma because I think concrete class injection is generally frowned upon by many folks.
tl;dr
Should dependency injection always be done with interfaces only, even when certain classes are unlikely to change, and hence, backing it by interface seems to add unwanted complexity?
You're right, Dependency Injection start to be useful as soon as there's more than one implementation. I understand that you have only one concrete implementation but if you follow developpement bests practices you'll want to unit test every class. And if a BarService depends on your FooService, you will write a unit test BarServiceTest that rely on a fake implementation of FooService (a mock or something like that).
In other words, as soon as you write unit test your app you end up with to implementations of your service : the real one used at runtime, the fake one used for unit testing (or a single implementation but configured differently depending on the context).
Just couple of things.
Dependency injection (DI) !== Inversion of Control (IoC) !== Dependency Inversion Principle (DIP)
I can't recall better (being same brief and explanatory) reading on the topic other than this
Second aspect is language and(or) tools dependent. Certainly I can't speak of all the languages and their tools-stack available, but there might be some where test-doubling an interface would be a better approach than generating a double as a child class of the class being mocked.
So my personal (and subjective) answer for
Should dependency injection always be done with interfaces only, even
when certain classes are unlikely to change, and hence, backing it by
interface seems to add unwanted complexity?
is definitely 'no' because of unneeded complexity in classes structure. Besides, doing DI usually means some kind of dependency injection container is used to manage dependencies, which in turn means extra configuration efforts.
Personally, I introduce interfaces by intent only when I really do have such an intent explicitly. All other interfaces that appear in code are just extractions during development/refactoring process (in other words, I create such abstractions only when me or my code come to the need of those).

In Dependency Injection where is an object to be injected created?

If it was created by the class that is injecting it into the object that uses it then isn't it just moving object creation one step up the stack? And wouldn't this mean that all objects needed by lower level classes would need to be passed through each object one at a time until it reached the object that needed it?
All objects and their dependencies could be set up at the very beginning, but wouldn't this dent performance as objects will be hanging around until needed?
Yes, it is moving the object instantiation up the stack. But it is moving it up the stack to a place where you can make a better decision as to which implementation to actually use. If I want to replace my data access layer with a stubbed version to do performance testing of the business logic, I can without changing a single line of the business logic code.
There are may ways to inject your dependencies. In my case, I use constructor injection everywhere. Using this method, if a lower level class needs a dependency, it just puts the interface for that dependency in its constructor. No need to pass from a class higher up in the stack. If you need the same instance in both classes, then you should look at the lifestyle/scope of when registering your dependency into the container so that both classes happen to get passed the same instance.
Some DI implementations use lazy loading to instantiate their objects. (i.e. it's not until the object is attempted to be used that it is actually instantiated) Some do not. Also, you would need quite the large dependency graph to make a dent in performance. Keep your constructors simple and fast (a good practice anyway) and this will not be a problem, I assure you. And DI containers are smart about releasing objects that are no longer in use (again, pay special attention to lifestyle/scope).
I hope this helps.

How does Unity (et al) actually help with Dependency Injection

I have some questions about DI containers (Unity in particular) and how they actually aid in DI.
I believe I understand IoC/DI and have been using constructor based DI for some years. Usually with my use of DI it involved simply having a constructor on my class, say MyClassX that takes an interface as an argument say IDataService and then using the new operator to create an instance of an IDataService implementing class and pass it into MyClassX's constructor. This way MyClassX doesn't need to know the exact type of the IDataService it is using decoupling it from a specific type. Now correct me if I am wrong, but that's what I understand DI to be...though it does not have to be constructor based.
Now I have seen a stack of examples of Unity on the net, but I am finding it difficult to not only understand everything it does (it seems like a magic object factory to me) but also how it exactly aids in DI as I understand it. To me Unity seems more like a Factory implementation (or a Mock framework?) rather than anything to do specifically with DI. I think I have really missed something though and am waiting for an "ah ha" moment. I have done alot of Googling but examples don't help... I need an theoretical explanation.
Can someone explain to me what Unity is exactly for...the broad points of what it does and how it is related to DI as I understand it.
Your understanding of basic Dependency Injection is correct. Constructor injection is the most common pattern.
Some other DI Unity does:
Lifetime management – instance creation can be singleton, one per
thread, and other advanced models.
Handles dependency graphs - request a root object and Unity creates all its dependency’s
dependencies.
Enables method and property injection – requires a
Unity attribute in your business code (which I prefer to avoid)
Service locator pattern – generally considered an anti-pattern
1 and 2 are nice when you need them. I think #3 and #4 are to be avoided when possible because it adds dependencies in your code to your Unity container.
The big bang that you are missing is Aspect Oriented Programing enabled by Interception with Unity. This allows the implementation of cross cutting concerns. Logging is the classic example. If you want more, start reading all the Enterprise Library Call Handlers for exception handling, validation, etc. or just start searching the web for AOP.
When you combine constructor injection of dependencies with external implementation of cross cutting concerns, you can get very close to business objects that only contain business logic. In a large Enterprise development team, that’s a very big bang.
When the object graph is simple you may not see the obvious advantages of using a DI container.
Say you have a class MyClassX which depends on IExampleA, IExampleB. Now the Implementation of IExampleA and IExampleB may depend on some other classes and so on. Now, this kind of object graph is complex to handle manually when it comes to materialized/instantiate it.
This is where DI comes into play. Once registered(class and its depended classes), All you need to do is,
var myclassX = _container.Resolve<MyClassX>()
And, don't get me wrong here, DI can provide much more than just resolving dependency. For example managing the LifeStyle and LifeCycle of objects etc.

DI: How much to inject?

I'm writing my second real life application, which uses DI. Overall I think it have let to a better design. But there are some code smells, that I don't know how to solve.
I prefer to use constructor injection and have often observed that I need about 5 or more objects to be injected in the constructor. It seems to be too many, maybe it's a design problem, not getting the SRP right. But I think that my use of DI also is to be blamed.
I'm looking for "best practices" or "rule of thumb", in general I seem to inject everything, that isn't in the .Net framework, is that overdoing it?
To get things started, here are two examples of objects that I inject, but am uncertain about.
Objects that are true singletons like application configuration or those small util classes, do you inject them?
They seems to be injected very often, the only reason to inject them seems to be allow to change the value for testing, but Ayende seems to have solved the problem in another way: http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx.
Common objects such as logging, that are used in almost every object, should they be injected?
The rule of thumb I often use is that I inject things that are in the way of properly writing unit tests. When doing this you will sometimes end up abstracting away BCL classes (such as DateTime.Now, File, etc), and sometimes your own stuff. Good things to inject are services (such as ICustomerService, ICustomerUnitOfWorkFactory, or ICustomerRepository). Don't inject things like entities, DTOs and messages.
There are other reasons for injecting objects however, such as to be able to replace modules at a later time (for instance switch implementations for validation, UI, or O/RM), to allow parallel development within or across teams, and to lower maintenance.
I prefer to use constructor injection
and have often observed that I need
about 5 or more objects to be injected
in the constructor.
As you already noted yourself, having many dependencies could be caused by not adhering to the SRP. What you can do however, is grouping common dependencies with there logic into an aggregate service and inject that into consumers. Also see Mark Seemann's article about Aggregate Services.
Objects that are true singletons like
application configuration or those
small util classes, do you inject
them?
I am personally not a fan of the way Ayende proposes it. This is an Ambient Context, which is a specific sort of service locator construct. Doing this hides the dependency, because classes can call that static class without you having to inject it. Explicitly injecting it makes it much clearer that you need to unit test time. Besides that, it makes it hard to write tests for frameworks such as MSTest who tend to run tests in parallel. Without any countermeasures, it makes your tests very unreliable. A better solution -for the DateTime.Now example- is to have an IClock interface, as is suggested here. As you can see, that answer scores much higher than Ayende approach, that is shown in the same SO question.
Common objects such as logging, that
are used in almost every object,
should they be injected?
I inject them in my code, because that makes the dependencies clear. Note however, that in my code I still hardly ever have to inject a logger. Think hard about every line you want to log and it isn't really a failure (or a cross-cutting concern that should be placed elsewhere). I usually throw an exception when something happened that I didn't expect. It allows me to find bugs fast. Or to put it in other words: Don't filter, but fail fast. And please ask yourself: "Do I log too much?"
I hope this helps.
My personal rule of thumb is this:
inject it if you want it to be immutable
inject it if you want to be able to substitute it for testing purposes
Things like services can meet both of those criteria - the consumer should never change it, and you want to be able to substitute it come testing time. With the immutable items, you would still possibly have a property on the consuming object, but that property would only have a getter, not a setter. If you wanted to change the value you have to create a new instance of the object.
Should loggers be injected?
There is no reason to. Loggers are typically exposed via a static class, and are new'ed up from configuration entries, so even for testing purposes there is no need to inject them.
Should true singletons like application configuration be injected?
Once again, it is a globally accessible object which is easily modified for test purposes, so no need to inject. The only time i would inject this is if the consumer was 'disconnected'; i.e. created via reflection or called as a web service or remote object.
While DI is a nice pattern, too much of a good thing can still be unhealthy. If you sense a growing code smell, then examine each item you are injecting and ask yourself the question: Do i NEED to inject this parameter?
A good starting point is to inject Volatile Dependencies.
You may want to also inject Stable Dependencies for further loose coupling, but if you need to prioritize, Volatile Dependencies is the best place to start.
Concerning constructor over-injection, it's really just a symptom of breaking SRP: see this related question: How to avoid Dependency Injection constructor madness?

what's the point of Dependency Injection Frameworks?

I am sure that I am somewhat lost in this area... my understanding is that Dependency Injection means initializing something that is required by a class..so for instance.
If my controller is going to need a service and I want to be able to test it then I should define two Constructor methods for it... so, my question is... why do people use Frameworks to achieve this?? Im lost
public class CompaniesController : Controller
{
private ICompaniesService _service;
public CompaniesController()
{
_service = new CompaniesService();
}
public CompaniesController(ICompaniesService service)
{
_service = service;
}
A major reason is to better support unit testing and mocking out objects to create controlled tests.
By not specifying the implementation inside the class, you can 'inject' an implementation at run time. (In your example, the ICompaniesService interface).
At runtime, using an inversion of control/dependency injection container such as StructureMap, Unity or Castle Windsor, you can say "hey, anytime someone wants an instance of ICompaniesService give them a new CompaniesService object".
To unit test this class, you can mock our a ICompaniesService and supply it yourself to the constructor. This allows you to setup controlled methods on the mock object. If you couldn't do this, your unit tests for CompaniesController would be limited to using only the one implementation of your companies service, which could hit a live database etc, making your unit tests both slow and inconsistent.
People don't use a Dependency Injection Framework to generate the code that you provided in your example. That's still the work of the developer.
The Dependency Injection Framework is used when somebody calls the constructor. The Framework will Inject the concrete implementation of the ICompaniesService rather than the developer explicitly calling the constructor.
While it is a specific product, the nInject Homepage actually has some really good examples.
From Wikipedia:
Without the concept of dependency
injection, a consumer who needs a
particular service "ICompaniesService" in order to
accomplish a certain task would be
responsible for handling the
life-cycle (instantiating, opening and
closing streams, disposing, etc.) of
that service. Using the concept of
dependency injection, however, the
life-cycle of a service is handled by
a dependency provider/framework (typically a
container) rather than the consumer.
The consumer would thus only need a
reference to an implementation of the
service "ICompaniesService" that it needed in order to
accomplish the necessary task.
Read this one too:
What is dependency injection?
People use Dependency Injection frameworks because otherwise you have to write a metric ton of boring, repetitive factory classes (if using dependency injection, that is).
It can be done, it's just very, very annoying.
I think your understanding is only partly correct. Dependency Injection is "injecting"
a dependency of a component into it. Its a more specific form of inversion of control. During
this process some dependencies can also be initialized before injecting.
With DI, the onus of looking up the dependency is not on the component
(as in ServiceLoacator pattern) but upto the container in which the component is
running. The pattern has following advantages:
Dependency lookup code can be eliminated from the component.
Some frameworks providing auto-wiring, injecting saving you from manually creating your component
hierarchies (Answers one of your questions)
Allows you to interchange implementations of your dependencies. (without using Factories)
Testing (replacing dependencies with mock implementations)
In your code example, a dependency can be injected by a DI container at runtime via the second
constructor. Other forms of injections are also possible (depending on the DI container). e.g.
Field injection, setter injection, etc.
There's a good article by martin fowler who coined the DI term
You dont have to have a DI framework, but at some point in your codebase a concrete implementation is going to need to be instantiated and injected into your constructors/properties. It can get very messy if you dont have a DI framework, I recommend looking at Castle Windsor although as mentioned there are others that will perform the same functionality. Or if you could role your own....:)
I'll pitch in:
You can accomplish dependency injection simply by having a parameterized function definition.
However, in order to make that work consistently, everyone has to actually do that. Many find that's its easier to enforce the convention by using a factory design pattern.
Dependency injection frameworks solve the problem of reducing the boilerplate of writing those factories.
I would say that dependency injection through a factory, is non-ideal. In my opinion factories add an extra layer of indirection and in a sense make deterministic functions in-deterministic in the sense that they are now a function of the inputs, plus state from the rest of the program (your di setup) which you cannot see from the function definition alone. Factories make code harder as they add an extra layer of indirection I'd argue that in many cases it's really not too hard to follow the convention and manually inject classes via the function arguments. Again though, for a large codebase, it's probably easier to enforce the rule through a factory.
..that being said sometimes I do wonder if these large codebases would even be this large if they didn't write so many things which try to preemptively solve problems that they don't have in the first place.

Resources