C# Difference between factory pattern and IoC

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


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 ?


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.

链接地址: http://www.djcxy.com/p/77748.html

上一篇: C#中依赖倒置原则vs工厂模式

下一篇: C#工厂模式和IoC之间的区别