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.
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.
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.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.
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