OOD using IoC containers - how to build dependent objects?

I am trying to improve with IoC, DI and OOD to better test and loosen the connection.

Therefore, when we develop classes with heavy use of IoC and DI, we can use classes with several dependencies, for example

class Processor
{
    private IService1 m_Service1;
    private IService2 m_Service2;
    private IService3 m_Service3;

    //approach 1 
    public Processor(IService1 service1, IService2 service2, IService3 service3)
    {
        m_Service1 = service1;
        m_Service2 = service2;
        m_Service3 = service3;
    }
    //approach 2
    public Processor(IContainer container)
    {
        m_Service1 = container.Resolve<IService1>();
        m_Service2 = container.Resolve<IService2>();
        m_Service3 = container.Resolve<IService3>();
    }

    //approach 3
    public delegate Processor Factory();

}

It seems to me that there should be a normal approach. We can leave the constructor with 3 parameters, but if we create the application using autofac (for example), most likely it will rarely be used differently than by resolving types from some container instance, such as

    Processor proc = new Processor(
 container.Resolve<IService1>(),
 container.Resolve<IService2>(),
 container.Resolve<IService3>());

so I think approach 2 is better when we depend on several types from the container. In any case, we will have to add a link to autofac somewhere, so why not do it now?

Autofac factory

http://code.google.com/p/autofac/wiki/DelegateFactories

var processorFactory = container.Resolve<Processor.Factory>();
Processor processor = processorFactory.Invoke();

, 3 - , .

IoC, , 1,2,3. .

, 1 , , , 1.. , .

- , Ive ( )

ServiceLocator, , , :

public class ServiceLocatorObject
{
        private IService1 m_Service1;
        private IService2 m_Service2;
        private IService3 m_Service3;
        public IService1 Service1 {get {return m_Service1;}}
        public IService2 Service2 {get {return m_Service2;}}
        public IService3 Service3 {get {return m_Service3;}}

        public ServiceLocatorObject(IService1 service1, IService2 service2, IService3 service3)
        {
            m_Service1 = service1;
            m_Service2 = service2;
            m_Service3 = service3;
        }
}

//approach 4
public Processor(ServiceLocatorObject servicesToUse)
{
    m_Services = servicesToUse;
}

, ( , ), , 100 . , 3- . DI not ServiceLocator. , .

?

+5
3

- ( . ).

, MUCH , , , , - -, , .

: http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx

, 1 Process CLEARLY , , - . .... , .

, IContainer, ... , , , .

+6

JeffN825 , , , :

Processor proc = new Processor(
    container.Resolve<IService1>(),
    container.Resolve<IService2>(),
    container.Resolve<IService3>());

, :

Processor proc = container.Resolve<Processor>();
+6

, . 2 , IoC, . 3 , - Factory . 1 , , IoC.

0
source

All Articles