525
votes

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?

29
Can't these two approaches compliment each other: using Dependency Injection to inject factory classes?Richard Ev
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?gideon
@gideon wouldn't that force you to compile your app, or at least the module containing the factory class?lysergic-acid
@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.gideon
Check out this great answer: stackoverflow.com/questions/4985455/… - he words it very well and provides code samples.Luis Perez

29 Answers

301
votes

When using a factory your code is still actually responsible for creating objects. By DI you outsource that responsibility to another class or a framework, which is separate from your code.

231
votes

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.

208
votes

Dependency Injection

Instead of instantiating the parts itself a car asks for the parts it needs to function.

class Car
{
    private Engine engine;
    private SteeringWheel wheel;
    private Tires tires;

    public Car(Engine engine, SteeringWheel wheel, Tires tires)
    {
        this.engine = engine;
        this.wheel = wheel;
        this.tires = tires;
    }
}

Factory

Puts the pieces together to make a complete object and hides the concrete type from the caller.

static class CarFactory
{
    public ICar BuildCar()
    {
        Engine engine = new Engine();
        SteeringWheel steeringWheel = new SteeringWheel();
        Tires tires = new Tires();
        ICar car = new RaceCar(engine, steeringWheel, tires);
        return car;
    }   
}

Result

As you can see, Factories and DI complement each other.

static void Main()
{
     ICar car = CarFactory.BuildCar();
     // use car
}

Do you remember goldilocks and the three bears? Well, dependency injection is kind of like that. Here are three ways to do the same thing.

void RaceCar() // example #1
{
    ICar car = CarFactory.BuildCar();
    car.Race();
}

void RaceCar(ICarFactory carFactory) // example #2
{
    ICar car = carFactory.BuildCar();
    car.Race();
}

void RaceCar(ICar car) // example #3
{
    car.Race();
}

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.

This Google Tech Talk by Misko Hevery is amazing and is the basis of what I derived my example from. http://www.youtube.com/watch?v=XcT4yYu_TTs

61
votes

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.

40
votes

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.

27
votes

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".

22
votes

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.

From: http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html

17
votes

Theory

There are two important points to consider:

  1. Who creates objects

    • [Factory]: You have to write HOW object should be created. You have separate Factory class which contains creation logic.
    • [Dependency Injection]: In practical cases are done by external frameworks (for example in Java that would be spring/ejb/guice). Injection happens "magically" without explicite creation of new objects
  2. What kind of objects it manages:

    • [Factory]: Usually responsible for creation of stateful objects
    • [Dependency Injections] More likely to create stateless objects

Practical example how to use both factory and dependency injection in single project

  1. What we want to build

Application module for creating order which contains multiple entries called orderline.

  1. Architecture

Let's assume we want to create following layer architecture:

enter image description here

Domain objects may be objects stored inside database. Repository (DAO) helps with retrievar of objects from database. Service provides API to other modules. Alows for operations on order module

  1. Domain Layer and usage of factories

Entities which will be in the database are Order and OrderLine. Order can have multiple OrderLines. Relationship between Order and OrderLine

Now comes important design part. Should modules outside this one create and manage OrderLines on their own? No. Order Line should exist only when you have Order associated with it. It would be best if you could hide internal implementaiton to outside classes.

But how to create Order without knowledge about OrderLines?

Factory

Someone who wants to create new order used OrderFactory (which will hide details about the fact how we create Order).

enter image description here

Thats how it will look inside IDE. Classes outside domain package will use OrderFactory instead of constructor inside Order

  1. Dependency Injection Dependency injection is more commonly used with stateless layers such as repository and service.

OrderRepository and OrderService are managed by dependency injection framework. Repository is responsible for managing CRUD operations on database. Service injects Repository and uses it to save/find correct domain classes.

enter image description here

16
votes

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.

13
votes

I know this question is old but i would like to add my five cents,

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!!

Anyway, the comment section if open for you to kill me.

6
votes

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.

4
votes

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.

3
votes

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"

The little kingdoms' governing bodies are "Factories"

The big government is the "Dependency Injector".

3
votes

You can have a look at this link for a comparison of the two (and others) approaches in a real example.

Basically, when requirements change, you end up modifying more code if you use factories instead of DI.

This is also valid with manual DI (i.e. when there isn't an external framework that provides the dependencies to your objects, but you pass them in each constructor).

3
votes

Most answers here explain conceptual difference and implementation details of both. However I was unable to find explanation about difference in application which IMO is the most important and the OP asked about. So let me reopen this topic...

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

Exactly. In 90% cases you can obtain object reference using either Factory or DI and usually you end up with latter. In another 10% cases using Factory is only correct way. These cases include obtaining objects by variable at runtime parameters. Like this:

IWebClient client = factoryWithCache.GetWebClient(url: "stackoverflow.com",
        useCookies: false, connectionTimeout: 120);

In this case getting client from DI is not possible (or at least requires some ugly workaround). So as a general rule to make decision: if a dependency can be obtained without any runtime calculated parameters then DI is preferred, otherwise use Factory.

3
votes

With a factory you can group related interfaces, So If the parameters passed can be grouped in a factory then its also a good solution for constructor overinjection look at this code *):

public AddressModelFactory(IAddressAttributeService addressAttributeService,
        IAddressAttributeParser addressAttributeParser,
        ILocalizationService localizationService,
        IStateProvinceService stateProvinceService,
        IAddressAttributeFormatter addressAttributeFormatter)
    {
        this._addressAttributeService = addressAttributeService;
        this._addressAttributeParser = addressAttributeParser;
        this._localizationService = localizationService;
        this._stateProvinceService = stateProvinceService;
        this._addressAttributeFormatter = addressAttributeFormatter;
    }

Look at the constructor, you only have to pass the IAddressModelFactory there, so less parameters *):

 public CustomerController(IAddressModelFactory addressModelFactory,
        ICustomerModelFactory customerModelFactory,
        IAuthenticationService authenticationService,
        DateTimeSettings dateTimeSettings,
        TaxSettings taxSettings,
        ILocalizationService localizationService,
        IWorkContext workContext,
        IStoreContext storeContext,
        ICustomerService customerService,
        ICustomerAttributeParser customerAttributeParser,
        ICustomerAttributeService customerAttributeService,
        IGenericAttributeService genericAttributeService,
        ICustomerRegistrationService customerRegistrationService,
        ITaxService taxService,
        CustomerSettings customerSettings,
        AddressSettings addressSettings,...

You see in CustomerController a lot of parameters passed, Yes you can see this as constructor overinjection but this is how DI works. And no nothing is wrong with the CustomerController.

*) Code is from nopCommerce.

3
votes

In simple terms Dependency Injection vs Factory method implies push vs pull mechanism respectively.

Pull mechanism : class indirectly have dependency on Factory Method which in turn have dependency on concrete classes.

Push mechanism : Root component can be configured with all dependent components in a single location and thus promoting high maintenance and loose coupling.

With Factory method responsibility still lies with class (though indirectly) to create new object where as with dependency injection that responsibility is outsourced (at the cost of leaking abstraction though)

2
votes

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.

Check this link :Dependency Injection

2
votes

Binoj,

I don't think you have to choose one over the other.

The act of moving a dependent class or interface to a class constructor or setter follows the DI pattern. The object you pass to the constructor or set can be implemented with Factory.

When to use? Use the pattern or patterns that are in your developer wheelhouse. What do they feel the most comfortable with and find easiest to understand.

2
votes

I believe, 3 important aspects govern objects and their usage:
1. Instantiation (of a class together with initialisation if any).
2. Injection (of the instance so created) where it's required.
3. Life cycle management (of the instance so created).

Using Factory pattern, the first aspect (instantiation) is achieved but the remaining two is questionable. The class that uses other instances must hardcode the factories (instead of instances being created) which hinders loose coupling abilities. Moreover, life cycle management of instances becomes a challenge in a large application where a factory is used in multiple places (particularly, if the factory doesn't manage the life cycle of the instance it returns, it gets ugly).

Using a DI (of IoC pattern) on the other hand, all the 3 are abstracted outside the code (to the DI container) and the managed bean needs nothing about this complexity. Loose Coupling, a very important architectural goal can be achieved quiet comfortably. Another important architectural goal, the separation of concerns can be achieved much better than factories.

Whereas the Factories may be suitable for small applications, large ones would be better to chose DI over factories.

1
votes

My thoughts:

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.

1
votes

An Injection Framework is an implementation of the Factory Pattern.

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.

1
votes

Factory Design Pattern

The factory design pattern is characterized by

  • An Interface
  • Implementation classes
  • A factory

You can observe few things when you question yourself as below

  • When will the factory create object for the implementation classes - run time or compile time?
  • What if you want to switch the implementation at run time? - Not possible

These are handled by Dependency injection.

Dependency injection

You can have different ways in which you can inject dependency. For simplicity lets go with Interface Injection

In DI ,container creates the needed instances, and "injects" them into the object.

Thus eliminates the static instantiation.

Example:

public class MyClass{

  MyInterface find= null;

  //Constructor- During the object instantiation

  public MyClass(MyInterface myInterface ) {

       find = myInterface ;
  }

  public void myMethod(){

       find.doSomething();

  }
}
1
votes

From a face value they look same

In very simple terms, Factory Pattern, a Creational Pattern helps to create us an object - "Define an interface for creating an object". If we have a key value sort of object pool (e.g. Dictionary), passing the key to the Factory (I am referring to the Simple Factory Pattern) you can resolve the Type. Job done! Dependency Injection Framework (such as Structure Map, Ninject, Unity ...etc) on the other hand seems to be doing the same thing.

But... "Don't reinvent the wheel"

From a architectural perspective its a binding layer and "Don't reinvent the wheel".

For an enterprise grade application, concept of DI is more of a architectural layer which defines dependencies. To simplify this further you can think of this as a separate classlibrary project, which does dependency resolving. The main application depends on this project where Dependency resolver refers to other concrete implementations and to the dependency resolving.

Inaddition to "GetType/Create" from a Factory, most often than not we need more features (ability to use XML to define dependencies, mocking and unit testing etc.). Since you referred to Structure Map, look at the Structure Map feature list. It's clearly more than simply resolving simple object Mapping. Don't reinvent the wheel!

If all you have is a hammer, everything looks like a nail

Depending on your requirements and what type of application you build you need to make a choice. If it has just few projects (may be one or two..) and involves few dependencies, you can pick a simpler approach. It's like using ADO .Net data access over using Entity Framework for a simple 1 or 2 database calls, where introducing EF is an overkill in that scenario.

But for a larger project or if your project gets bigger, I would highly recommend to have a DI layer with a framework and make room to change the DI framework you use (Use a Facade in the Main App (Web App, Web Api, Desktop..etc.).

1
votes

I think these are orthogonal and can be used together. Let me show you an example I recently came across at work:

We were using the Spring framework in Java for DI. A singleton class (Parent) had to instantiate new objects of another class (Child), and those had complex collaborators:

@Component
class Parent {
    // ...
    @Autowired
    Parent(Dep1 dep1, Dep2 dep2, ..., DepN depN) {
        this.dep1 = dep1;
        this.dep2 = dep2;
    }

    void method(int p) {
        Child c = new Child(dep1, dep2, ..., depN, p);
        // ...
    }
}

In this example, Parent has to receive DepX instances only to pass them to the Child constructor. Problems with this:

  1. Parent has more knowledge of Child than it should
  2. Parent has more collaborators than it should
  3. Adding dependencies to Child involves changing Parent

This is when I realized a Factory would fit here perfectly:

  1. It hides all but the true parameters of the Child class, as seen by Parent
  2. It encapsulates the knowledge of creating a Child, which can be centralized in the DI configuration.

This is the simplified Parent class and the ChildFactory class:

@Component
class Parent {
    // ...
    @Autowired
    Parent(ChildFactory childFactory) {
        this.childFactory = childFactory;
    }

    void method(int p) {
        Child c = childFactory.newChild(p);
        // ...
    }
}

@Component
class ChildFactory {
    // ...
    @Autowired
    Parent(Dep1 dep1, Dep2 dep2, ..., DepN depN) {
        this.dep1 = dep1;
        this.dep2 = dep2;
        // ...
        this.depN = depN;
    }

    Child newChild(int p) {
        return new Child(dep1, dep2, ..., depN, p);
    }
}
1
votes

You use dependency injection when you exactly know what type of objects you require at this point of time. While in case of factory pattern, you just delegate the process of creating objects to factory as you are unclear of what exact type of objects you require.

0
votes

DI gives you a composition root, which is a single centralized location for wiring up your object graph. This tends to make object dependencies very explicit, because objects ask for exactly what they need and there is only one place to get it.

A composition root is a clean and straightforward separation of concerns. Objects being injected should have no dependency on the DI mechanism, whether that be a third-party container or a DIY DI. The DI should be invisible.

Factories tend to be more distributed. Different objects use different factories and the factories represent an additional layer of indirection between the objects and their actual dependencies. This additional layer adds its own dependencies to the object graph. Factories are not invisible. A Factory is a middleman.

For this reason, updating factories is more problematic: since factories are a dependency of the business logic, modifying them can have a ripple effect. A composition root is not a dependency of the business logic, so it can be modified in isolation.

The GoF mentions the difficulty of updating Abstract Factories. Part of their explanation is quoted in an answer here. Contrasting DI with Factories also has a lot in common with the question, Is ServiceLocator an anti-pattern?

Ultimately, the answer of which to choose may be opinionated; but I think it boils down to a Factory being a middleman. The question is whether that middleman pulls its weight by adding additional value beyond just supplying a product. Because if you can get that same product without the middleman, then why not cut the middleman out?

A diagram helps to illustrate the difference. DI vs Factory

-1
votes

I use both to create an Inversion Of Control strategy with more readability for developers who need to maintain it after me.

I use a Factory to create my different Layer objects (Business, Data Access).

ICarBusiness carBusiness = BusinessFactory.CreateCarBusiness();

Another developer will see this and when creating an Business Layer object he looks in BusinessFactory and Intellisense gives the developer all the possible Business Layers to create. Doesn't have to play the game, find the Interface I want to create.

This structure is already Inversion Of Control. I am no longer responsible for creating the specific object. But you still need to ensure Dependency Injection to be able to change things easily. Creating your own custom Dependency Injection is ridiculous, so I use Unity. Within the CreateCarBusiness() I ask Unity to Resolve which class belongs to this and it’s lifetime.

So my code Factory Dependency Injection structure is:

public static class BusinessFactory
{
    public static ICarBusiness CreateCarBusiness()
    {
       return Container.Resolve<ICarBusiness>();
    }
}

Now I have the benefit of both. My code is also more readable for other developers as towards scopes of my objects I use, instead of Constructor Dependency Injection which just says every object is available when the class is created.

I use this to change my Database Data Access to a custom coded Data Access layer when I create Unit Tests. I don’t want my Unit Tests to communicate with databases, webservers, e-mail servers etc. They need to test my Business Layer because that’s where the intelligence is.

-4
votes

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.