Dependency injection and object creation - dependency-injection

When I use dependency injection, I create all objects at the very beginning of the program.
I end up having to carry dependencies through a lot of constructors, although it would be more easy to create them somewhere earlier.
The pattern of factories comes to mind. Factory can be passed in the constructor to not violate DI.
But isn't this an anti-pattern / violating of DI? Since Factory creates a concrete implementation of the object?
What are the approaches to create objects without breaking DI?

When practicing DI, there is no need or requirement to construct all objects at startup; that's a design choice or perhaps a design constraint in your particular environment. In fact, lazy initialization with DI is the norm—not the exception.
But the consequence of lazy initialization of object graphs is that you typically have some factory-like behavior somewhere in the application.
Many application types, like web application frameworks, provide a factory abstraction that you can implement or override that allows you to create the necessary objects for the request that comes in.
If you do this, and create the object structure specific for a request, just in time when a request comes in, I'd say that in most cases there is no need for postponing the creation of other objects for that request. This means there's no need for injecting any factory classes into the classes of your application. I'd say that in most cases, Abstract Factories are a Design Smell.
But there are exceptions, though, and the argument that Abstract Factories should be reviewed with suspicion, doesn't mean that you don't need factory-like behavior somewhere inside your code. Whenever you're doing message dispatching, for instance, where an incoming message gets dispatched to one or multiple handlers, where many handler classes exist in the application, requires lazy initialization of classes, and requires factory-like behavior. This, however, can be hidden behind abstractions that are implemented inside the Composition Root, which prevents application code from depending on an Abstract Factory.
But that said, not all application frameworks expose factory abstractions for you to implement, and as I said, there are always exceptions to the rule.

Related

When to use property 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.

IOC issue: Too many Abstract Factories for Runtime data dependent classes

I have recently started to use DI in one of my projects. For runtime dependent classes, I created corresponding Abstract factories. After following this pattern I end up having too many abstract factories, almost one for each of my class.
Is it common to end up having too many abstract factories when using IOC ?
Scenario: Suppose I get an "Entity" object from a database. There are 10 different use cases a user could perform on this entity object. For each of the usecase I have a different class to handle it. In some cases a given use case could have sub use case components which may also need the entity object.
As these classes are dependent on runtime entity object, I had to create abstract factory for each one of them. Finally I wire the construction instructions in the IOC container.
Is there an alternative way of doing it. I just feel creating all these factories is waste of time, ESPECIALLY when all the sub classes are dependent on the same entity object.
I am inclined on having a single factory / builder class registered for my scenario with IOC container. This factory would create the required object graph for my scenario. I see IOC as a tool to help implement DI concept. Not using IOC container all the way may not be bad as long as I am observing DI via a custom builder / factory.
I wanted to know what do you guys think about this approach?
It sounds like you are suffering from an overabundance of 1:1 interfaces. When that happens it's often a sign that one should stop and think about the Reused Abstractions Principle.
Perhaps you can redesign your interfaces so that there are less factories and more commands.

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.

When to use Dependency Injection

I've had a certain feeling these last couple of days that dependency-injection should really be called "I can't make up my mind"-pattern. I know this might sound silly, but really it's about the reasoning behind why I should use Dependency Injection (DI). Often it is said that I should use DI, to achieve a higher level of loose-coupling, and I get that part. But really... how often do I change my database, once my choice has fallen on MS SQL or MySQL .. Very rarely right?
Does anyone have some very compelling reasons why DI is the way to go?
Two words, unit testing.
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up 'test' data.
DI is very useful for decoupling your system. If all you're using it for is to decouple the database implementation from the rest of your application, then either your application is pretty simple or you need to do a lot more analysis on the problem domain and discover what components within your problem domain are the most likely to change and the components within your system that have a large amount of coupling.
DI is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain.
How relevant it is to your project depends upon the expected lifespan of your code. Depending on the type of work you're doing zero reuse from one project to the next for the majority of code you're writing might actually be quite acceptable.
An example for use the use of DI is in creating an application that can be deployed for several clients using DI to inject customisations for the client, which could also be described as the GOF Strategy pattern. Many of the GOF patterns can be facilitated with the use of a DI framework.
DI is more relevant to Enterprise application development in which you have a large amount of code, complicated business requirements and an expectation (or hope) that the system will be maintained for many years or decades.
Even if you don't change the structure of your program during development phases you will find out you need to access several subsystems from different parts of your program. With DI each of your classes just needs to ask for services and you're free of having to provide all the wiring manually.
This really helps me on concentrating on the interaction of things in the software design and not on "who needs to carry what around because someone else needs it later".
Additionally it also just saves a LOT of work writing boilerplate code. Do I need a singleton? I just configure a class to be one. Can I test with such a "singleton"? Yes, I still can (since I just CONFIGURED it to exist only once, but the test can instantiate an alternative implementation).
But, by the way before I was using DI I didn't really understand its worth, but trying it was a real eye-opener to me: My designs are a lot more object-oriented as they have been before.
By the way, with the current application I DON'T unit-test (bad, bad me) but I STILL couldn't live with DI anymore. It is so much easier moving things around and keeping classes small and simple.
While I semi-agree with you with the DB example, one of the large things that I found helpful to use DI is to help me test the layer I build on top of the database.
Here's an example...
You have your database.
You have your code that accesses the database and returns objects
You have business domain objects that take the previous item's objects and do some logic with them.
If you merge the data access with your business domain logic, your domain objects can become difficult to test. DI allows you to inject your own data access objects into your domain so that you don't depend on the database for testing or possibly demonstrations (ran a demo where some data was pulled in from xml instead of a database).
Abstracting 3rd party components and frameworks like this would also help you.
Aside from the testing example, there's a few places where DI can be used through a Design by Contract approach. You may find it appropriate to create a processing engine of sorts that calls methods of the objects you're injecting into it. While it may not truly "process it" it runs the methods that have different implementation in each object you provide.
I saw an example of this where the every business domain object had a "Save" function that the was called after it was injected into the processor. The processor modified the component with configuration information and Save handled the object's primary state. In essence, DI supplemented the polymorphic method implementation of the objects that conformed to the Interface.
Dependency Injection gives you the ability to test specific units of code in isolation.
Say I have a class Foo for example that takes an instance of a class Bar in its constructor. One of the methods on Foo might check that a Property value of Bar is one which allows some other processing of Bar to take place.
public class Foo
{
private Bar _bar;
public Foo(Bar bar)
{
_bar = bar;
}
public bool IsPropertyOfBarValid()
{
return _bar.SomeProperty == PropertyEnum.ValidProperty;
}
}
Now let's say that Bar is instantiated and it's Properties are set to data from some datasource in it's constructor. How might I go about testing the IsPropertyOfBarValid() method of Foo (ignoring the fact that this is an incredibly simple example)? Well, Foo is dependent on the instance of Bar passed in to the constructor, which in turn is dependent on the data from the datasource that it's properties are set to. What we would like to do is have some way of isolating Foo from the resources it depends upon so that we can test it in isolation
This is where Dependency Injection comes in. What we want is to have some way of faking an instance of Bar passed to Foo such that we can control the properties set on this fake Bar and achieve what we set out to do, test that the implementation of IsPropertyOfBarValid() does what we expect it to do, i.e. return true when Bar.SomeProperty == PropertyEnum.ValidProperty and false for any other value.
There are two types of fake object, Mocks and Stubs. Stubs provide input for the application under test so that the test can be performed on something else. Mocks on the other hand provide input to the test to decide on pass\fail.
Martin Fowler has a great article on the difference between Mocks and Stubs
I think that DI is worth using when you have many services/components whose implementations must be selected at runtime based on external configuration. (Note that such configuration can take the form of an XML file or a combination of code annotations and separate classes; choose what is more convenient.)
Otherwise, I would simply use a ServiceLocator, which is much "lighter" and easier to understand than a whole DI framework.
For unit testing, I prefer to use a mocking API that can mock objects on demand, instead of requiring them to be "injected" into the tested unit from a test. For Java, one such library is my own, JMockit.
Aside from loose coupling, testing of any type is achieved with much greater ease thanks to DI. You can put replace an existing dependency of a class under test with a mock, a dummy or even another version. If a class is created with its dependencies directly instantiated it can often be difficult or even impossible to "stub" them out if required.
I just understood tonight.
For me, dependancy injection is a method for instantiate objects which require a lot of parameters to work in a specific context.
When should you use dependancy injection?
You can use dependancy injection if you instanciate in a static way an object. For example, if you use a class which can convert objects into XML file or JSON file and if you need only the XML file. You will have to instanciate the object and configure a lot of thing if you don't use dependancy injection.
When should you not use depandancy injection?
If an object is instanciated with request parameters (after a submission form), you should not use depandancy injection because the object is not instanciated in a static way.

Resources