Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

Once someone told me that its how you use it that makes a difference!

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?

Would be really nice if this question had an answer with some code in it! I still don't see how DI would be beneficial/different from use a factory for creation? You'll only need to replace that one line in the factory class to change which obj/implementation is created?
–
gideonDec 14 '10 at 16:30

2

@gideon wouldn't that force you to compile your app, or at least the module containing the factory class?
–
lysergic-acidApr 28 '12 at 8:03

1

@liortal yep that's right. Did a long study on DI since that comment and now I understand the DI takes the factory method one step ahead.
–
gideonApr 28 '12 at 9:06

I would suggest to keep the concepts plain and simple. Dependency Injection is more of a architectural pattern for loosely coupling software components. Factory pattern is just one way to separate the responsibility of creating objects of other classes to another entity. Factory pattern can be called as a tool to implement DI. Dependency injection can be implemented in many ways like DI using constructors, using mapping xml files etc.

That's true that Factory Pattern is one of the way implementing Dependency Injection. Another benefit using Dependency Injection against Factory Pattern is that DI Frameworks would give you flexibility of how to register your abstractions against your concrete types. Such as Code as Config, XML or Auto Configuration. That flexibility will give you manage lifetime of your objects or decide how and when to register your interfaces.
–
Teoman shipahiOct 6 '14 at 3:35

Example #1 - This is the worst because it completely hides the dependency. If you looked at the method as a black box you would have no idea it required a car.

Example #2 - This is a little better because now we know we need a car since we pass in a car factory. But this time we are passing too much since all the method actually needs is a car. We are passing in a factory just to build the car when the car could be built outside the method and passed in.

Example #3 - This is ideal because the method asks for exactly what it needs. Not too much or too little. I don't have to write a MockCarFactory just to create MockCars, I can pass the mock straight in. It is direct and the interface doesn't lie.

Sometimes you don't know ICar's characteristics beforehand (like special tyres, depending on the weather). In those cases you'd go with #2 and instruct the ICarFactory to spill out a car with that attribute. A lot of DI is done because there's no sane way to isolate your components with testing. #2 and #3 accomplish that.
–
PeerBrJan 21 at 16:55

This isn't dependency injection, this is just passing in the dependencies. Dependency injection has just one class that knows what the dependencies are, so the caller who wants a RaceCar doesn't have to know that it requires a car or a carFactory. Hiding the dependency (as in example 1) is the /point/ of dependency injection. It isn't supposed to expose dependencies; it's supposed to keep the code providing them in one place.
–
Phil GoetzJun 1 at 18:11

1

@PhilGoetz What you are describing sounds more like the Service Locator pattern. They have similar goals, in that they aim to decouple services from their consumers. However, there are many disadvantages to the Service Locator pattern. Mainly, hiding dependencies is not a good thing. The consumer still needs to get its dependencies, but instead of defining a clear interface, they are passed in 'secretly' and rely on global state. In the example, the consumer has no idea about the factory, it only asks for what it needs and doesn't have to concern itself with how that need is constructed.
–
DespertarJun 2 at 4:16

There are problems which are easy to solve with dependency injection which are not so easily solved with a suite of factories.

Some of the difference between, on the one hand, inversion of control and dependency injection (IOC/DI), and, on the other hand, a service locator or a suite of factories (factory), is:

IOC/DI is a complete ecosystem of domain objects and services in and of itself. It sets everything up for you in the way you specify. Your domain objects and services are constructed by the container, and do not construct themselves: they therefore do not have any dependencies on the container or on any factories. IOC/DI permits an extremely high degree of configurability, with all the configuration in a single place (construction of the container) at the topmost layer of your application (the GUI, the Web front-end).

Factory abstracts away some of the construction of your domain objects and services. But domain objects and services are still responsible for figuring out how to construct themselves and how to get all the things they depend on. All these "active" dependencies filter all the way through all the layers in your application. There is no single place to go to configure everything.

Life cycle management is one of the responsibilities dependency containers assume in addition to instantiation and injection. The fact that the container sometimes keep a reference to the components after instantiation is the reason it is called a "container", and not a factory. Dependency injection containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object.

I believe DI is a type of abstraction layer on factories, but they also provide benefits beyond abstraction. A true factory knows how to instantiate a single type and configure it. A good DI layer provides the ability, through configuration, to instantiate and configure many types.

Obviously, for a project with a few simple types that requires relatively stable business logic in their construction, the factory pattern is simple to understand, implement, and works well.

OTOH, if you have a project containing numerous types whose implementations you expect to change often, DI gives you the flexibility through its configuration to do this at runtime without having to recompile your factories.

One disadvantage of DI is that it can not initialize objects with logic. For example, when I need to create a character that has random name and age, DI is not the choice over factory pattern. With factories, we can easily encapsulate the random algorithm from object creation, which supports one of the design patterns called "Encapsulate what varies".

I think that dependency injection (DI) is in many ways like a configurable Factory Pattern (FP), and in that sense anything that you could do with DI you will be able to do it with such factory.

Actually, if you use spring for example, you have the option of autowiring resources (DI) or doing something like this:

MyBean mb = ctx.getBean("myBean");

And then use that 'mb' instance to do anything. Isn't that a call to a factory that will return you an instance??

The only real difference I notice between most of the FP examples is that you can configure what "myBean" is in an xml or in another class, and a framework will work as the factory, but other than that is the same thing, and you can have a certainly have a Factory that reads a config file or gets the implementation as it needs.

And if you ask me for my opinion (And I know you didn't), I believe that DI does the same thing but just adds more complexity to the development, why?

well, for one thing, for you to know what is the implementation being used for any bean you autowire with DI, you have to go to the configuration itself.

but... what about that promise that you will not have to know the implementation of the object you are using? pfft! seriously? when you use an approach like this... aren't you the same that writes the implementation?? and even if you don't, arent you almost all the time looking at how the implementation does what it is supposed to do??

and for one last thing, it doesn't matter how much a DI framework promises you that you will build things decoupled from it, with no dependencies to their classes, if you are using a framework you build everything aroud it, if you have to change the approach or the framework it will not be an easy task... EVER!... but, since you buil everything around that particular framework instead of worrying of whats the best solution for your business, then you will face a biiig problen when doing that.

In fact, the only real business application for a FP or DI approach that I can see is if you need to change the implementations being used at runtime, but at least the frameworks I know do not allow you to do that, you have to leave everything perfect in the configuration at development time an if you need that use another approach.

So, if I have a class that performs differently in two scopes in the same application (lets say, two companies of a holding) I have to configure the framework to create two different beans, and adapt my code to use each. Isn't that the same as if I would just write something like this:

MyBean mb = MyBeanForEntreprise1(); //In the classes of the first enterprise
MyBean mb = MyBeanForEntreprise2(); //In the classes of the second enterprise

the same as this:

@Autowired MyBean mbForEnterprise1; //In the classes of the first enterprise
@Autowired MyBean mbForEnterprise2; //In the classes of the second enterprise

And this:

MyBean mb = (MyBean)MyFactory.get("myBeanForEntreprise1"); //In the classes of the first enterprise
MyBean mb = (MyBean)MyFactory.get("myBeanForEntreprise2"); //In the classes of the second enterprise

In any case you will have to change something in your application, whether classes or configuration files, but you will have to do it an redeploy it.

Wouldn't it be nice to do just something like this:

MyBean mb = (MyBean)MyFactory.get("mb");

And that way, you set the code of the factory to get the right implementation at runtime depending on the logged user enterprise?? Now THAT would be helpful. You could just add a new jar with the new classes and set the rules maybe even also at runtime (or add a new config file if you leave this option open), no changes to existing classes. This would be a Dynamic factory!

wouldn't that be more helpful than having to write two configurations for each enterprise, and maybe even having two different applications for each??

You can tell me, I don't need to do the switch at runtime ever, so I configure the app, and if I inherit the class or use another implementation I just change the config and redeploy. Ok, that can also be done with a factory. And be honest, how many times do you do this? maybe only when you have an app that's going to be used somewhere else in your company, and you are going to pass the code to another team, and they will do things like this. But hey, that can also be done with the factory, and would be even better with a dynamic factory!!

Too many developers think that Dependency Injection frameworks are created to bring something new. As you well explain, traditional factories (most often abstract factory) can play the same role of dependency inversion. Inversion vs Injection? For me, the only "benefit" of Dependency Injection framework is that we haven't to change/recompile the code (since most often configurable with XML like Spring) when a dependency is added/changed. Why avoid to recompile? In order to avoid some potential human errors while changing dependency/factory. But with our great IDEs, refactoring plays well :)
–
Mik378Feb 5 '13 at 13:02

With dependency injection the client does not need to get its dependencies on its own, its all prepared beforehand.

With factories, someone has to call those to get the generated objects over to the place where they are needed.

The difference lies mostly in this one line where calling the factory and fetching the constructed object is done.

But with factories you have to write this 1 line everywhere you need such an object. With DI you just have to create the wiring (relation between usage and created object) once and just rely on the presence of the object afterward everywhere. On the other side, DI often requires a bit more (how much depends on the framework) work on the preparation side.

i believe that DI is a way of configurings or instantianting a bean. The DI can be done in many ways like constructor, setter-getter etc.

Factory pattern is just another way of instantiating beans. this pattern will be used mainly when you have to create objects using factory design pattern,because while using this pattern you dont configure the properties of a bean, only instantiate the object.

I had the same question as soon as I read about DI and ended up at this post.
So finally this is what I understood but please correct me if am wrong.

"Long ago there were little kingdoms with their own governing bodies controlling and taking decisions based on their own written rules. Later on formed a big government eliminating all these little governing bodies which has one set of rules(constitution) and are implemented through courts"

IOC is a concept which is implemented by two ways. Dependency creation and dependency injection, Factory/Abstract factory are the example of dependency creation. Dependency injection is constructor, setter and interface. The core of IOC is to not depend upon the concrete classes, but define the abstract of methods(say an Interface/abstract class) and use that abstract to call method of concrete class. Like Factory pattern return the base class or interface. Similariliy dependency injection use base class/interface to set value for objects.

The reason Dependency Injection (DI) and Factory Patterns are similar is because they are two implementations of Inversion of Control (IoC) which is a software architecture. Put simply they are two solutions to the same problem.

So to answer the question the main difference between the Factory pattern and DI is how the object reference is obtained. With dependency injection as the name implies the reference is injected or given to your code. With Factory pattern your code must request the reference so your code fetches the object. Both implementations remove or decouple the linkage between the code and the underlying class or type of the object reference being used by the code.

It's worth noting that Factory patterns (or indeed Abstract Factory patterns which are factories that return new factories that return object references) can be written to dynamically choose or link to the type or class of object being requested at run time. This makes them very similar (even more so than DI) to Service Locator pattern which is another implementation of the IoC.

The Factory design pattern is quite old (in terms of Software) and has been around for a while. Since the recent popularity of the architectural pattern IoC it is having a resurgence.

I guess when it comes to IoC design patterns: injectors be injecting, locators be locating and the factories have been refactored.

@ArK my original answer was a little facetious and didn't going into enough detail to answer the question without existing knowledge of IoC architectural pattern. I've edit the answer to clarify and fully answer the OP.
–
Tom MaherMar 19 at 11:41

It all depends upon your requirements. If you have need to implement the factory pattern in an application, it's highly likely your requirements will be met by one of the myriad of injection framework implementations out there.

You should only roll out your own solution if your requirements cannot be met by any of the 3rd party frameworks. The more code you write, the more you code you have to maintain. Code is a liability not an asset.

Arguments over which implementation you should use is not as fundamentally important as understanding the architectural needs of your application.

Dependecy Injection: pass collaborators as parameters to the constructors.
Dependency Injection Framework: a generic and configurable factory to create the objects to pass as parameters to the constructors.

Using dependency injection is much better in my opinion if you are:
1. deploying your code in small partition, because it handles well in decoupling of one big code.
2. testability is one of the case DI is ok to use because you can mock easily the non decoupled objects. with the use of interfaces you can easily mock and test each objects.
3. you can simultaneously revised each part of the program without needing to code the other part of it since its loosely decoupled.