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?
Yes it will be "wasted", but the nature of that waste depends on how its set up:
Service2
is always created as a new instance; that's fairly expensiveService2
is in single instance mode, all its doing is fetching an existing instance (super cheap)Class
is in single instance mode; its fetching that instance and not injecting anything newMoreover, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With