I'm fairly new to the DI concept, but I have been using it to some extent in my designs - mainly by 'injecting' interfaces into constructors and having factories create my concrete classes. Okay, it's not configuration-based - but it's never NEEDED to be.
I started to look at DI frameworks such as Spring.NET and Castle Windsor, and stumbled across this blog by Ayende.
What I got from this is
A) DI frameworks are awesome, but
B) It means we don't have to worry about how our system is designed in terms of dependencies.
For me, I'm used to thinking hard about how to loosely-couple my system but at the same time have some sort of control over dependencies.
I'm a bit scared of losing this control, and it being just a free-for-all. ClassA needs ClassB = no problem, just ask and ye shall receive! Hmmm.
Or is that just the point and this is the future and I should just go with it?
Thoughts?
One basic OO principle is that you want your code to depend on interfaces and not implementations, DI is how we do that. Historically, here is how it evolved:
People initially created classes they depended upon by "new'ing" them:
IMyClass myClass = new MyClass();
Then we wanted to remove instantiation so there were static methods to create them:
IMyClass myClass = MyClass.Create();
Then we no longer depended on the lifecycle of the class, but still depended on it for instantiation, so then we used the factory:
IMyClass myClass = MyClassFactory.Create();
This moved the direct dependency from the consuming code to the factory, but we still had the dependency on MyClass indirectly, so we used the service locator pattern like this:
IMyClass myClass = (IMyClass)Context.Find("MyClass");
That way we were only dependent on an interface and a name of a class in our code. But it can be made better, why not depend simply on an interface in our code? We can with dependency injection. If you use property injection you would simply put a property setter for the interface you want in your code. You then configure what the actual dependency is outside of your code and the container manages the lifecycle of that class and your class.
I wouldn't say that you don't have to think about dependencies, but using an IoC framework allows you to change the types which fulfill the dependencies with little or no hassle, since all the wiring is done in a central place.
You still have to think about what interfaces you need and getting them right is not always a trivial matter.
I don't see how a loosely coupled system could be considered lazily designed. If you go through all the trouble of getting to know an IoC framework, you're certainly not taking the shortcut.
I think that ideally, if you already have a loosley coupled system.., using a container will only move the place where you take the dependencies out of your code making them softer and let your system depend on the container building your object graph.
In reality, attempting to use the the container will probably show you that your system is not as loosley coupled as you thought it was.. so in this way, it may help you to create a better design.
Well, i'm a newbie at this subjet.. so maybe i'm not that right.
Cheers.
I must be high, because I thought the whole point of dependency injection is that the code that does stuff simply declares its dependencies so that someone who's creating it will know what to create with it for it to operate correctly.
How dependency injection makes you lazy is maybe it forces someone else to deal with dependencies? That's the whole point! That someone else doesn't need to be really someone else; it just means the code you write doesn't need to be concerned with dependencies because it declares them upfront. And they can be managed because they are explicit.
Edit: Added the last sentence above.
Dependency injection can be a bit difficult to get used to - instead of a direct path through your code, you end up looking at seemingly unconnected objects, and a given action traces it's path through a series of these objects whose coupling seems, to be kind, abstract.
It's a paradigm shift similar to getting used to OO. The intention is that your objects are written do have a focused and single responsibility, using the dependent objects as they're declared by the interface and handled by the framework.
This not only makes loose coupling easier, it makes it almost unavoidable, or at least nearly so, which makes it much simpler to do things like run your object in a mock environment - The IOC container is taking the place of the run environment.
I would disagree and say they lead to better design in many cases. Too often devs create components that do too much and have too many dependencies. With IOC developers i find tend to migrate to a better way of thinking and produce smaller simpler components that can be assembled together into an app.s
If they follow the spirit and do tests, they will further refine your components. Both exercises force you to write better testable components which fits very well with how IOC containers work.
You still have to worry. My team use Castle Windsor in our current project. It annoys me that it delays dependency lookup from compile time to runtime.
Without Castle Windsor, you write code and if you haven't sorted your dependencies out. Bang, the compiler will complain. With Castle Windsor you configure the dependencies in an xml file. They're still there, just separated out from the bulk of your code. The problem is, your code can compile fine if you make a mess of defining the dependencies. But, at runtime, Castle Windsor looks up a concrete classes to service requests for an interface by using reflection. If the dependency can't be found, you get an error at runtime.
I think Castle Windsor does check the dependencies exist when its initialized so that it can throw an error pretty quick. But, it's still annoying when using a strongly typed language that this fuss can't be sorted out at runtime.
So... anyway. Dependencies still seriously matter. You'll all most certainly pay more attention to them using DI than before.
We wrote custom DI framework, thought it took some time getting it right but it all worth the effort. We have divided the who systems into layers and the dependency injection in each layer is bound by rules. E.g. In the Log layer, CUD and BO interfaces cannot be injected.
We are still contemplating over the rules and some of these change every week while the others are remain the same.
Related
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.
I have been reading alot about dependency injection thinking that it may be some really advanced way to program, but I can't see the difference between just avoiding global state, as when there is no global state then you are forced to pass in all dependencies to objects.
Can someone please explain to me as I think I may be missing the point about what dependency injection is?
Dependency injection is about decoupling code.
When you avoid the use of globals by passing arguments you are decoupling code. You are removing the dependency the code has on the globals.
You can generalize this decoupling to more than just the avoidance of globals. Take the following code:
def foo(arg):
return ClassBar(arg).attr
foo(1)
The function foo is dependent on or tightly coupled to ClassBar. The reason this is not good is you will be forced to update foo when:
the arguments to constructing ClassBar change
you want to change ClassBar to something else
another piece of code wants to access attr from a different object
If the code was rewritten:
def foo(instanceBar):
return instanceBar.attr
foo(ClassBar(1))
You've pushed the coupling up to the caller. This removed the dependency from the definition of foo. This frees you from having to update foo in the cases outlined above. The more of your code that is decoupled, the fewer code changes you'll need to make.
What I understand about dependency injection is that you leave out the details of creating an object and only declare that such an object is needed. A framework for example will set this object later on before it's needed.
So the value here is the separation of concerns. This is useful for testing when you will inject a mockup of the real object.
Dependency injection is a way for implementing the inversion of control pattern for avoiding global state for dependency resolution. You can use the inversion of control pattern with or without dependency-injection. Yes not using global variables is an important part of the equation weather you use dependency-injection or not.
Dependency injection is really nothing more than if you were to write a program in a bottom up style where the most top level portion of the application resolved dependencies for all subsystems. Say I had a program with a dependency injection configuration like:
<bean id="world" class="com.game.World" start-method="play">
<property name="player1" ref="player1"/>
<property name="player2" ref="player2"/>
</bean>
<bean id="player1" class="com.game.LocalPlayer"/>
<bean id="player2" class="com.game.NetworkPlayer/>
That would really be no different than if you created the objects by hand:
public static void main() {
World world = new World();
world.player1 = new LocalPlayer();
world.player2 = new NetworkPlayer();
world.play();
}
Using dependency injection simply means writing code like the above is handled for you. In this simple example you can't make much of a case for using it over just using code, but in larger programs it does save you a lot of time. It also prevents you or team members from taking shortcuts because it's not as wide open as when you write code.
Dependency-injection frameworks change your program from imperative style code to a declarative-style language for dependencies. So you're writing a program through this declarative language and you can augment that with lots of other features.
Features like having the framework resolve order of construction and cycle dependencies for you. Declaring external configuration and injection of values into your declared objects (i.e. property files, XML configuration, etc) which is really nice. All of these together makes dependency injection frameworks quite compelling to use over doing all of this on your own.
Another thing is that dependency injection generally creates singleton objects. In situations like services and DAOs, you would never want to have more than one object. Its also nice to have it instantiated already(generally on app startup, in spring), so you can use whenever needs arise.
Assuming you are a good coder, you want to be able to test and replace your parts system easily. The best way to do this is with a modular design. That is to say you want to break down your problem into smaller problems that you can solve and keep bug free.
By using dependency injection, you are able to come up with these smaller components, test them and link them together in a standard way. This in tern results in slicker, decoupled design. In turn, your project doesn't grind begin to slow as you are never working in high complexity code (at least in theory) this productivity remains high.
If you are a skilled developer you can make use of the singleton pattern (and others) to get most of the same benefits. However, your entire team needs to have this same skill or once again you get coupled design and low throughput.
Using dependency injection looks to be like using Windows registry. You load up the registry with things you want and then pull them out and use them in some module.
However, it breaks Object oriented code.
Say you have 20 items in your Dependency registry. A database, a logger, an exception handler and so on.
Now in a given module you have NO IDEA which of these dependency services your module uses. Your context is further lost because you don't know what will be in the dependency registry at the time you run the code!
I cannot see any benefit here. It simply makes debugging impossible.
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?
I've read a lot about IoC and DI, but I'm not really convinced that you gain a lot by using them in most situations.
If you are writing code that needs pluggable components, then yes, I see the value. But if you are not, then I question whether changing a dependency from a class to an interface is really gaining you anything, other than more typing.
In some cases, I can see where IoC and DI help with mocking, but if you're not using Mocking, or TDD then what's the value? Is this a case of YAGNI?
I doubt you will have any hard data on it, so I will add some thoughts on it.
First, you don't use DI (or other SOLID principles) because it helps you do TDD. Its the other way around, you do TDD because it helps you with the design - which usually means you get code that follow those principles.
Discussing why to use interfaces is a different matter, see: https://stackoverflow.com/questions/667139/what-is-the-purpose-of-interfaces.
I will assume you agree that having your classes do many different things results in messy code. Thus, I am assuming you are already going for SRP.
Because you have different classes that do specific things, you need a way to relate them. If you relate them inside the classes (i.e. the constructors), you get plenty of code that uses specific versions of the classes. This means that making changes to the system will be hard.
You are going to need to change the system, that's a fact of software development. You can call YAGNI about not adding specific extra features, but not on that you won't be needing to change the system. In my case that's something really important as I do weekly sprints.
I use a DI framework where configuration is done through code. With a really small code configuration, you hook up lots of different relations. So, when you take away the discussion on interface vs. concrete classes, you are actually saving typing not the other way around. Also for the cases a concrete class is on the constructor, it hooks it up automatically (I don't have to configure) building the rest of the relations. It also allows me to control some objects life time, in particular I can configure an object to be a Singleton and it hands a single instance all the time.
Also note that just using these practices isn't more overhead. Using them for the first times, is what causes the overhead (because of the learning process + in some cases mind set change).
Bottom line: you ain't gonna need to put all those constructor calls all over the place to go faster.
The most significant gains from DI are not necessarily due to the use of interfaces. You do not actually need to use interfaces to have beneficial effects of dependency injection. If there's only one implementation you can probably inject that directly, and you can use a mix of classes and interfaces.
You're still getting loose coupling, and quite a few development environments you can introduce that interface with a few keypresses if needed.
Hard data on the value of loose coupling I cannot give, but it's been a vision in textbooks for as long as I can remember. Now it's real.
DI frameworks also give you some quite amazing features when it comes to hierarchical construction of large structures. Instead of looking for the leanest DI framework around, I'd recommend you look for a full-featured one. Less isn't always more, at least when it comes to learning about new ways of programming. Then you can go for less.
Apart from testing also the loose coupling is worth it.
I've worked on components for an embedded Java system, which had a fixed configuration of objects after startup (about 50 mostly different objects).
The first component was legacy code without dependency injection, and the subobjects where created all over the place. Now it happened several times that for some modification some code needed to talk to an object which was only available three constructors away. So what can you do but add another parameter to the constructor and pass it through, or even store it in a field to pass it on later. In the long run things became even more tangled than they already where.
The second component I developed from scratch, and used dependency injection (without knowing it at the time). That is, I had one factory which constructed all objects and injected then on a need to know basis. Adding another dependency was easy, just add it to the factory and the objects constructor (or add a setter to avoid loops). No unrelated code needed to be touched.
I've been using StructureMap recently and have enjoyed the experience thoroughly. However, I can see how one can easily get carried away with interfacing everything out and end up with classes that take in a boatload of interfaces into their constructors. Even though that really isn't a huge problem when you're using a dependency injection framework, it still feels that there are certain properties that really don't need to be interfaced out just for the sake of interfacing them.
Where do you draw the line on what to interface out vs just adding a property to the class?
The main problem with dependency injection is that, while it gives the appearance of a loosely coupled architecture, it really doesn't.
What you're really doing is moving that coupling from the compile time to the runtime, but still if class A needs some interface B to work, an instance of a class which implements interface B needs still to be provided.
Dependency injection should only be used for the parts of the application that need to be changed dynamically without recompiling the base code.
Uses that I've seen useful for an Inversion of Control pattern:
A plugin architecture. So by making the right entry points you can define the contract for the service that must be provided.
Workflow-like architecture. Where you can connect several components dynamically connecting the output of a component to the input of another one.
Per-client application. Let's say you have various clients which pays for a set of "features" of your project. By using dependency injection you can easily provide just the core components and some "added" components which provide just the features the client have paid.
Translation. Although this is not usually done for translation purposes, you can "inject" different language files as needed by the application. That includes RTL or LTR user interfaces as needed.
Think about your design. DI allows you to change how your code functions via configuration changes. It also allows you to break dependencies between classes so that you can isolate and test objects easier. You have to determine where this makes sense and where it doesn't. There's no pat answer.
A good rule of thumb is that if its too hard to test, you've got some issues with single responsibility and static dependencies. Isolate code that performs a single function into a class and break that static dependency by extracting an interface and using a DI framework to inject the correct instance at runtime. By doing this, you make it trivial to test the two parts separately.
Dependency injection should only be used for the parts of the
application that need to be changed dynamically without recompiling
the base code
DI should be used to isolate your code from external resources (databases, webservices, xml files, plugin architecture). The amount of time it would take to test your logic in code would almost be prohibitive at a lot of companies if you are testing components that DEPEND on a database.
In most applications the database isn't going to change dynamically (although it could) but generally speaking it's almost always good practice to NOT bind your application to a particular external resource. The amount involve in changing resources should be low (data access classes should rarely have a cyclomatic complexity above one in it's methods).
What do you mean by "just adding a property to a class?"
My rule of thumb is to make the class unit testable. If your class relies on the implementation details of another class, that needs to be refactored/abstracted to the point that the classes can be tested in isolation.
EDIT: You mention a boatload of interfaces in the constructor. I would advise using setters/getters instead. I find that it makes things much easier to maintain in the long run.
I do it only when it helps with separation of concerns.
Like maybe cross-project I would provide an interface for implementers in one of my library project and the implementing project would inject whatever specific implementation they want in.
But that's about it... all the other cases it'd just make the system unnecessarily complex
Even with all the facts and processes in the world.. every decision boils down to a judgment call - Forgot where I read that
I think it's more of a experience / flight time call.
Basically if you see the dependency as a candidate object that may be replaced in the near future, use dependency injection. If I see 'classA and its dependencies' as one block for substitution, then I probably won't use DI for A's deps.
The biggest benefit is that it will help you understand or even uncover the architecture of your application. You'll be able to see very clearly how your dependency chains work and be able to make changes to individual parts without requiring you to change things that are unrelated. You'll end up with a loosely coupled application. This will push you into a better design and you'll be surprised when you can keep making improvements because your design will help you keep separating and organizing code going forward. It can also facilitate unit testing because you now have a natural way to substitute implementations of particular interfaces.
There are some applications that are just throwaway but if there's a doubt I would go ahead and create the interfaces. After some practice it's not much of a burden.
Another item I wrestle with is where should I use dependency injection? Where do you take your dependency on StructureMap? Only in the startup application? Does that mean all the implementations have to be handed all the way down from the top-most layer to the bottom-most layer?
I use Castle Windsor/Microkernel, I have no experience with anything else but I like it a lot.
As for how do you decide what to inject? So far the following rule of thumb has served me well: If the class is so simple that it doesn't need unit tests, you can feel free to instantiate it in class, otherwise you probably want to have a dependency through the constructor.
As for whether you should create an interface vs just making your methods and properties virtual I think you should go the interface route either if you either a) can see the class have some level of reusability in a different application (i.e. a logger) or b) if either because of the amount of constructor parameters or because there is a significant amount of logic in the constructor, the class is otherwise difficult to mock.