Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Dependency Injection a good idea when not all instances are used?

I'm a supporter of using Dependency Injection on your application, despite some people consider it add unnecessary complexity to the code. In the past days I've wondered that, for some scenarios, there may be some waste when using DI.

Let me explain it with code examples:

Using DI

public class Class 
{
    private Service1 service1;
    private Service2 service2;

    public MyClass (Service1 service1, Service2 service2) 
    {
        this.service1 = service1;
        this.service2 = service2;
    }

    private int SampleMethod() 
    {
        Console.WriteLine("doing something with service 1");
        service1.DoSomething();
        return 0;
    }

    private int SampleMethod2() 
    {
        Console.WriteLine("doing something with service 2");
        service2.DoSomethingElse();
        return 1;
    }
}

What if I rarely call SampleMethod2 and I will be injecting it every single time a Class instance is needed? Wouldn't that be wasting resources?

I got this question a few days ago and I'm trying to figure out the response. Is it easier not using DI and let every method to create the instance they need when they get used in order to avoid this "waste"?

Is this a justified "waste" thanks to the decoupling that DI provides?

like image 749
Raul Gomez Rodriguez Avatar asked Mar 05 '23 23:03

Raul Gomez Rodriguez


1 Answers

Yes it will be "wasted", but the nature of that waste depends on how its set up:

  • If Service2 is always created as a new instance; that's fairly expensive
  • If Service2 is in single instance mode, all its doing is fetching an existing instance (super cheap)
  • If Class is in single instance mode; its fetching that instance and not injecting anything new

Moreover, this would suggest a violation of SRP. Perhaps Class should be split into two objects, one that depends on Service1 and one that depends on Service 2 (or even both).

Regardless of the above, the "waste" is only important if it actually impacts your application, the benefits of DI vastly outweigh these kinds of problems.

like image 140
BradleyDotNET Avatar answered Mar 08 '23 18:03

BradleyDotNET