Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a dependency is only used in a single method, should I inject it or use service location?

I am bit new to dependency injection & came across subjected question while working.

Lets say I have a class 'Employee' which has one method this method say 'Promote' gets conditionally called that too on rarest scenario.

'Promote' method uses an object of 'ValueAddition', now is it best practice to have this objected injected via constructor & user global object or should I resolve the dependency in method itself?

What is recommended best practice? or any pointer on the life time of resolved dependency would be helpful.

like image 233
user4903642 Avatar asked Oct 14 '25 08:10

user4903642


1 Answers

In general you should always look to inject dependencies rather than use service location (ie, resolving a dependency directly from the inversion of control container). There's a great, pretty well known blog article here called "Service Locator is an Anti-Pattern" that can help clarify the reasons.

You may run into other issues as you expand that seem to point you to using service location. In general, you really should design around those issues instead of falling back to service location.

  • I only need the object in one method. Consider moving the functionality of the method to a different object. For example, maybe the Promote() method should be on an IEmployeePromoter where you resolve that and it takes the special object. Then you'd call Promote(Employee) and pass in the employee rather than changing the dependencies for an Employee. Sometimes your inversion of control container will have a way to generate a factory (like Func<T> or Lazy<T>) to help you defer resolution until you actually need it.
  • I have way too many dependencies. Usually this means your object is doing too much. The single responsibility principle can help you refactor your objects to be a more manageable size. Smaller objects generally need fewer dependencies because they have far fewer concerns to manage.

There's a good amount of documentation and books out there on the pattern of dependency injection. It might be good to widen the scope of your search to looking at the patterns and practices in general when not applied to a particular framework (or even language) and it can help inform you of best practices in your own code.

like image 145
Travis Illig Avatar answered Oct 18 '25 02:10

Travis Illig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!