jeudi 8 mars 2018

Lazy initialization of dependencies injected into constructor

I have a class where i am injecting two service dependencies. I am using unity container.

 public interface IOrganizer{
    void Method1();
    void Method2();
    void Method3();
}

public class Organizer : IOrganizer{

private IService1 _service1;
private IService2 _service2;
public Organizer(Iservice1 service1, IService2 service2){
_service1 = service1;
_service2 = service2;}

public void Method1(){/*makes use of _service1 and _service2 both to serve the purpose*/}
public void Method2(){/*makes use of only _service1 to serve the purpose*/}
public void Method3(){/*makes use of only _service2 to serve the purpose*/}
}

While it all works, but somehow it smells because when when I am only invoking Method1 and Method2, unity unnecessarily creates an instance of another not required service. The code snippet here is just sample for explanation purpose. In real situation object graph of these injected services itself is quite deep.

Is there a better way to design and address this kind of scenario.

Aucun commentaire:

Enregistrer un commentaire