Last active
August 29, 2015 14:01
-
-
Save erikringsmuth/6543597228740c630577 to your computer and use it in GitHub Desktop.
DI vs. Module Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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