dimanche 25 octobre 2015

How does Dependency Injection using ServiceLocator advantageous over creating dependent objects explicity in constructor

It is possible to resolve the dependency by having a default constructor initializing the dependent object as below.

public class Foo:IFoo
{
public void disp()
{
//some code
}
}

public class MyClass
{
    IFoo ifoo;

    public MyClass()
    {
     this(new Foo());
    }

    public  MyClass(IFoo i)
    {
      this.ifoo = i;
    }

    void method1()
    {
     ifoo.disp();
    }
}

Similarly, all dependencies could be resolved by having 2 constructors as above, with which the unit testing framework could use the parameterized constructor straight away.

In this case, what is the advantage of implementing IunityContainer and service locator to create an instance.

Aucun commentaire:

Enregistrer un commentaire