Dependency Injection vs Factory Pattern [closed]
Asked Answered
P

31

576

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?

Posthumous answered 17/2, 2009 at 17:3 Comment(9)
Can't these two approaches compliment each other: using Dependency Injection to inject factory classes?Buddhism
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?Blemish
@Blemish wouldn't that force you to compile your app, or at least the module containing the factory class?Eucalyptol
@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.Blemish
Check out this great answer: #4985955 - he words it very well and provides code samples.Brianabriand
Have you ever seen a use of dependency injection that didn't use factories? That would be weird, since dependency injection means putting the code to create an object in just one place, which imposes all the complexity / abstraction / pain-in-the-ass overhead of a factory. Wouldn't it be silly to use DI but not factories?Untread
To add my two cents, if one is interested in how dependency injection can be helpful in a coffee shop theme, I have written an article on that here: digigene.com/design-patterns/dependency-injection-coffeeshopScoundrelly
The answer with the most votes makes no sense. The factory design pattern uses the dependency inversion principle, which DOES outsource code instantiation to another class. hence, his answer makes no sense.Thriftless
To make good dependency injection you have to rely on factories, this allow you to make a Composition Root, a top overlay that wire all your decoupled components together fitting your implementation case, you can take a look at Di-Ninja library, this is a good source code exemple for explaining the goals of dependency injection github.com/di-ninja/di-ninjaTameratamerlane
I
324

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.

Indistinctive answered 17/2, 2009 at 17:14 Comment(11)
The DI pattern does not require any frameworks. You can do DI by manually writing factories which do DI. DI frameworks just make it easier.Gehman
@Perpetualcoder - Thanks @Esko - Dont get caught up on the word framework meaning some advanced 3rd party library.Indistinctive
Could you say what the advantage is of giving DI the creation responsibility? In case of the factory method you need to change one line of code in there to change which implementation is created right?Blemish
@giddy - correct, it is no longer a code problem it is a configuration problemIndistinctive
+1 @willcode thanks! So you have to change config/xml files instead. I see. The wiki link en.wikipedia.org/wiki/… defines the factory pattern as Manually-Injected DependencyBlemish
I don't get the advantage of changing 1 line of XML vs changing 1 line of code. Could you elaborate?Costotomy
@Indistinctive so what's the point of using IoC instead of Abstract Factory? Since when something changes in our code (for example: new dependency is added) we have to change the configuration. The same problem we have with Abstract Factory. So, as RafaelEyng stated, what is the advantage of changing 1 line of XML vs changing 1 line of code ?Dyer
@RafaelEyng the only advantage I see with using XML-config is: you don't need to recompile to apply the changes. But there are other methods of dependency injection, which don't use XML as a configuration file. In those cases I don't see any advantage of using IoC vs Abstract FactoryDyer
Repeat the OP answer replacing "DI" with "factory", still makes sense.Camenae
The factory design pattern uses the dependency inversion principle, which DOES outsource code instantiation to another class. hence, this answer makes no sense.Thriftless
It makes no sense to arbitrarily consider a factory to be part of your code, while arbitrarily considering DI to be separate from your code.Scilla
D
246

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.

Daggerboard answered 17/2, 2009 at 17:10 Comment(5)
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.Emmott
Factory pattern offers higher-level abstraction than DI. A factory can offer configuration options just as DI does, but it can also choose to hide all those configuration details, so that the factory can decide to switch to a completely different implementation without the client knowing. DI on its own does not allow this. DI requires the client to specify the changes he wants.Bondie
Nice answer. Many are confusing with that question: "What pattens should I choose?" In fact, design patterns are just a way to solve problem at proper situations. If you don't know what design pattern you should use, or "Where should I implement the pattern?" then you don't need that at this time.Scanlan
I think it is more accurate to say Factory Pattern is a tool to implement IoC (not DI). Please note that DI is a form of IoCAraliaceous
@neuron, that's the only use case where manually implementing a factory is justified when a DI container is already available: when you want to hide the creation configuration details from the caller. Other than that, a DI container can perfectly serve as a factory and save you the effort of manually implementing one.Crafty
Z
242

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

Zellner answered 4/6, 2013 at 6:6 Comment(13)
Factory Pattern is injected as DI.Puzzlement
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.Deign
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.Untread
@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.Zellner
Number 1 isn't an issue of not knowing the method uses a car. It is actually a valid abstraction when you as the caller don't care about the what and how of the method you are calling.Mcspadden
@MatthewWhited Most design decisions have a trade off. With DI, you gain flexibility, transparency and a more testable system, but at the cost of exposing your guts. Many people find this an acceptable trade off. This is not to say that DI is always the best solution and this question is not about that. The example is meant to show the difference between DI and factory pattern by showing some good and bad uses of each.Zellner
This isn't a DI pattern, this is just an implementation of IoC. DI uses a ServiceLocator to determine the right dependency and inject it into the constructor during the object creation, your code only segregates the creation of objects from your class scope.Hawkbill
@DiegoMendes What you are describing is a framework that automates DI. The ServiceLocator as you call it does the DI for you. What I'm showing is the pattern itself which does not require any fancy frameworks. See https://mcmap.net/q/15453/-what-is-dependency-injection, or see en.wikipedia.org/wiki/…: "[list of frameworks] support dependency injection but are not required to do dependency injection". Also, "An injection is the passing of a dependency to a dependent object". You're over complicating a beautifully simple concept.Zellner
"Example #3 - This is ideal because the method asks for exactly what it needs". Usually the best methods just call a single method inside? How can this be ideal when its just pointless . This is the problem with DI, people just spend more time writing boilerplate code and not anything usefull.Squeamish
@FilipCordas This is just an example of how to properly use DI, so it focuses on the method interface, not the implementation. ICar could be an encryption algorithm or something that persists data. These are just two of thousands of things you may not want to hard code concrete classes for. DI has trade offs like all things, so you have to use your best judgement on when the flexibility you gain is worth the indirection, etc.Zellner
@Zellner Yes it could but it doesn't. My issue when talking DI is that people are talking like it solves all problems in every situation even when it would be better solutions to the same situation like in the example you gave. And ServiceLocator pattern is not DI pattern both are IOC patterns but the two are different.Squeamish
The real reason to pass in a factory is if the object you're constructing will need to build multiple instances of the dependency over the course of its lifetime. Which then is really two different needs - "I need a car" vs. "I need to build multiple cars over my lifespan." I guess another scenario would be if you need to defer construction, but even then I'd probably prefer to just have the dependency defer its intialization until use.Dowry
ICar car = new RaceCar(engine, steeringWheel, tires); Where is the RaceCar Class in this example ?Ostrowski
H
84

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.

Henriettahenriette answered 17/2, 2009 at 17:3 Comment(4)
This is the best answer... other answers either don't mention IoC or don't recognize that DI is a form of IoC.Araliaceous
Thanks, when I first studied IOC I almost screamed that this was just another form of the factory pattern, turns out they are really similar to each otherGerthagerti
Tom, I want to clear my head and I came to ask a questions but since it was already asked. Mmy view is that instead of using and worrying about FP, can I use DI almost all the time to decoupling the classes and to achive Open/Close principle. To me what I can achive with the service class in DI, I could also achive by FP but I will go with the DI approach it is because I seen some example where Factory pattern is implmeted but also DI was also implmented on the top of it with ServiceCollection that return IServiceProvider or manually created Service. So why bother with FP. What do you think?Lyse
@Lyse I think that's a good approach. DI is the favoured technic by modern frameworks such as ASP.NET Core. As mentioned before there is never going to be a one size fits all type of solution. There will always be a use case where you'll need to use Factory pattern in some way. And as you'll see most DI frameworks will support the use of Factory patterns in some format. So they are there as an extension point if you really do need them.Henriettahenriette
N
40

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.

Norfolk answered 17/2, 2009 at 17:16 Comment(0)
R
33

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

Rheo answered 17/2, 2009 at 17:3 Comment(0)
T
24

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

Teryl answered 17/2, 2009 at 17:3 Comment(0)
C
21

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, this is done by external frameworks (for example in Java that would be spring/ejb/guice). Injection happens "magically" without explicit creation of new objects.
  1. What kind of objects it manages:
  • [Factory]: Usually responsible for creation of stateful objects
  • [Dependency Injections]: More likely to create stateless objects

Practical example on how to use both factory and dependency injection in a 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 the following layered architecture:

enter image description here

Domain objects may be objects stored inside the database. Repository (DAO) helps with retriever of objects from the database. Service provides API to other modules. Allows 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 the 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 implementation 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

That's how it will look like inside an IDE. Classes outside the 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 the dependency injection framework. Repository is responsible for managing CRUD operations on the database. Service injects Repository and uses it to save/find correct domain classes.

enter image description here

Chromaticness answered 17/2, 2009 at 17:3 Comment(2)
Can you please clarify this? [Factory]: Usually responsible for creation of stateful objects [Dependency Injections] More likely to create stateless objects I don't understand whyMcbride
Stateful objects are likely to be in domain layer of application where you map your data to database you usually do not use dependency injection there. Factory is used often to create AggregateRoot from tree of complicated objectsChromaticness
O
16

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.

Olivette answered 17/2, 2009 at 17:13 Comment(0)
M
14

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.

Merrillmerrily answered 17/2, 2009 at 17:3 Comment(1)
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 :)Episcopal
C
6

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.

Carreno answered 17/2, 2009 at 17:3 Comment(0)
M
6

With a dependency injection framework the developer does not need to prepare and set dependencies of a class instance manually, it's all prepared beforehand.

With factories, the developer has to do this by hand and create the classes instance using those dependent objects.

The difference lies mostly in this one line where calling the factory and fetching the constructed object is done and in writing the factory method that creates and sets up everything (although it could be argued that with dependency injection frameworks this has also to be done to a certain extend, by wiring up and configuring the object relations).

Then with factories you have to call the factory everywhere you need such an object. With DI frameworks you mostly can rely on the presence of the object already at creation time of the class instance.

My opinion is that a factory method is more static as its implementation is rather fixed while a dependency injection framework is more dynamic as the actual composition of a class instance can change more easily (eg. for testing purposes) at runtinme.

Muster answered 17/2, 2009 at 17:12 Comment(2)
What you describe is not DI. You talk about DI freamwork that make for you the heavy lift of rewrite the code in compile time. The pattern him self dont have any connection to what you describeTenebrific
@yehonatanyehezkel updated text to better express that my answer relates to frameworks instead of design patternsMuster
N
4

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.

Northrup answered 17/2, 2009 at 17:3 Comment(1)
Yes, exactly. Almost all of the mentions of Dependency Injection (DI) in this Q&A misuse the term in contrast to this definition. A Dependency Injection Container (DIC) is the most common framework acting as a generic and configurable factory to create objects.Metalworking
Y
3

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)

Yehudit answered 17/2, 2009 at 17:3 Comment(1)
@RahulAgarwal, what does the last part mean, "at the cost of leaking abstraction though"? DI leaks abstraction in a way that Factory does not?Reiter
L
3

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.

Leighannleighland answered 17/2, 2009 at 17:3 Comment(0)
C
3

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.

Cafard answered 17/2, 2009 at 17:3 Comment(0)
A
3

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

Aircraftman answered 17/2, 2009 at 17:3 Comment(0)
R
3

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

Reclusion answered 17/2, 2009 at 17:3 Comment(1)
So WHEN does one codsider a previous little government to now be big? By what measure?Impish
I
2

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.

Incondensable answered 17/2, 2009 at 17:3 Comment(0)
M
2

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.

Manic answered 17/2, 2009 at 17:3 Comment(0)
N
2

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

Numbersnumbfish answered 17/2, 2009 at 18:1 Comment(0)
I
2

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.

Inchoation answered 17/2, 2009 at 19:2 Comment(0)
R
1

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

Reiter answered 17/2, 2009 at 17:3 Comment(0)
M
1

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);
    }
}
Mincey answered 17/2, 2009 at 17:3 Comment(0)
L
1

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

Lesalesak answered 17/2, 2009 at 17:3 Comment(0)
H
1

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();

  }
}
Holbrooke answered 17/2, 2009 at 17:3 Comment(0)
E
1

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.

Evangelista answered 17/2, 2009 at 17:3 Comment(0)
C
0

[Factory] -> There is a class which creates classes based on request parameters. After all, a "factory" makes "objects" for you also in the real world. You can ask your car vendor factory to make (for free :) ) a Tesla ver. 1 for you.

[DI] -> There is a (service) container which stores interfaces (contracted classes). You don't care to create objects. You just ask someone/somwhere to implement it, details and other stuff do not matter to you, the caller or the consumer.

DI is at the base of the "D" in SOLID principles.

Clipper answered 17/2, 2009 at 17:3 Comment(0)
A
-1

Factory pattern help us in making decision which object needs to create whereas Dependency injection helps to inject the concrete object.

Both are different. We can decide which object to return based on factory pattern. We can use dependeny injection to return the object instead of creating the object using new. In this way, factory pattern will not violate dependeny injection.

Antoinetteanton answered 17/2, 2009 at 17:3 Comment(0)
H
-1

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.

Herminiahermione answered 17/2, 2009 at 17:3 Comment(0)
C
-4

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.

Cita answered 17/2, 2009 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.