15

Possible Duplicate:
Dependency Injection vs Factory Pattern

Can someone please explain (with SIMPLE examples) of the difference between the factory pattern and Inversion of Control pattern. Preferably using .NET2.0

9
  • Do you mean "factory pattern" or "abstract factory pattern"? (The latter being closer in meaning to IoC.) Jan 24, 2011 at 12:05
  • Duplicate: stackoverflow.com/questions/557742/… Jan 24, 2011 at 12:20
  • 2
    @Mark The question may well be a duplicate but unfortunately it has no accepted answer.
    – Tim Lloyd
    Jan 24, 2011 at 12:22
  • 1
    @chibacity: Then the Q should explain why it is different clearly as an edit in your post. Also the levels of upvotes are such that the answers in the other thread are viable. Whether or not the asker has bothered to accept and/or follow up by explainign the missingn characteristics in the existing answers that would lead to an accept is not relevant. And if people feel it is, stick a bounty on it. Bottom line, it's a very similar question, so seconding VTC Jan 24, 2011 at 13:02
  • 1
    @Ruben Having had a think about it and asking a question on MSO, I agree. I think what's more important is that asking the same question multiple times fragments the question. It's better to close as a duplicate to direct back to a single source. Closing as a duplicate also brings attention back to the old question. I vote to close.
    – Tim Lloyd
    Jan 24, 2011 at 23:15

2 Answers 2

17

The factory pattern: the object which needs a reference to a service, should know about the factory that creates the Service:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject()
    {
        DalInstance = DalFactory.CreateSqlServerDal();
    }
}

The Ioc Pattern (or Dependency Injection) :

the object only needs to declare its need to the service, using any aspects of the Ioc Pattern (Constructor, setter, or interface ... etc) and the container will try to fulfill this need:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject(IDal _dalInstance)
    {
        DalInstance = _dalInstance;
    }
}

which means that in the factory pattern, the object decides which creation method (by choosing a specific concrete factory) to use, but the in the Ioc pattern, it is up to the container to choose.

of course this is not the only deference, but this is what is in my mind for the time being. correct me please if I'm wrong ?

1

The factory pattern is about getting the reference to a type, so somewhere in your code you would be calling into a factory to resolve something.

The Inversion of control pattern means that you would typically use an Ioc container to resolve dependencies for you. This could be in a similar way to a factory, or more typically you would use dependency injection to resolve the dependencies into the constructor or setters.

Not the answer you're looking for? Browse other questions tagged or ask your own question.