C# Difference between factory pattern and IoC

Eminem picture Eminem · Jan 24, 2011 · Viewed 12k times · Source

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

Answer

Nour picture Nour · Jan 24, 2011

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 ?