Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the $injector instance directly vs. obtaining dependencies as parameters

Within Angular, is it considered a good practice getting the dependencies directly from an $injector instance, rather than as parameters?

I have the problem that my controllers started having a lot of dependencies, so rather than:

myApp.controller(['$scope', 'Dep1', 'Dep2', 'Dep3', function($scope, Dep1, Dep2, Dep3) {
    ...
}]);

I would do:

myApp.controller(['$scope', '$injector', function($scope, $injector) {
    var Dep1 = $injector.get('Dep1');
    var Dep2 = $injector.get('Dep2');
    var Dep3 = $injector.get('Dep3');
}]);

I find it the same functionality-wise, but with much less clutter on the parameters. I suppose that this will make my components slightly less easy to test though, right?

What do you think?

like image 422
Preslav Rachev Avatar asked Mar 20 '26 11:03

Preslav Rachev


1 Answers

Based on my opinion and after reading the following posts:

Post 1

Post 2

Angular's documentation on DI (Dependency Injection)

Your second approach in order to minimize the long dependency list is considered as Service Locator Anti Pattern. See - Service locator AntiPattern

Using the Service Locator Anti Pattern is bad because it will make your life as a maintenance developer worse because you will need to use considerable amounts of brain power to grasp the implications of every change you make. Using the $injector obfuscates the actual dependencies of the resource (in this case controller) and kills maintainability.

In addition, according to angular's documentation the the preferable way is:

Using the inline array annotation (preferred)

If your controller is ending up using so many dependencies maybe you are doing something wrong, Maybe you broke the Single responsibility principle. consider:

  1. Delegate more of the logic to service(s) that are injected in
  2. Separate out into different controllers, so each only has (just about) 1 responsibility
like image 189
Or Guz Avatar answered Mar 22 '26 23:03

Or Guz



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!