Skip to content

Instantly share code, notes, and snippets.

@erikringsmuth
Last active August 29, 2015 14:01
Show Gist options
  • Save erikringsmuth/6543597228740c630577 to your computer and use it in GitHub Desktop.
Save erikringsmuth/6543597228740c630577 to your computer and use it in GitHub Desktop.
DI vs. Module Loader
// The DI pattern assumes that MyService will be a class or constructor function
import {MyService} from './myService';
@Inject(MyService)
export class MyThing {
constructor(myService) {
this.myService = myService;
}
someAction() {
this.myService; // the injected instance
}
}
// Here you can use DI to inject mocks and test
// Versus the module loading pattern where you can just return the service object. Javascript
// has objects aka singletons by default. The `new` keyword was a hack. Classes are better but
// still not necessary to create a "singleton".
import {myService} from './myService';
export class MyThing {
someAction() {
myService; // it's just an object
}
}
// Here you use Jest, injectr, or Squire to mock and test
Both of these approaches work. The DI pattern is more powerful. You can wire up more
complex objects as show here https://gist.github.com/domenic/5753428. On the other
hand, the module loading pattern is simple and you see exactly what's happening.
Mocking is just as easy. You just lose some of the wiring power that DI provides.
In my experience you typically don't need the extra layer of DI and you can get away
with the module loader by itself.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment