Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29149

DI design challenge with class which creates instances

I want to use Dependency Injection (DI) for one of my projects. I have written a basic DI lib which basically works as follows

let di = new DI();
di.register('screen', Screen);   // contract name, class ref
di.register('pixels', Pixels);

And you can create instances as follows:

let pixels = di.getInstance('pixels');

or with one addition parameter

let pixeks = di.getInstance('pixels', [arrayOfPixels]);

The problem I have now is with the Screen class:

export default class Screen() {
   getPixels() {
       // Get pixels from a canvas
       return new Pixels(pixels);
   }
}

the Screen class creates instances of Pixels. This is not in line with DI, so the question is how can I solve this in a correct way. If there is a design pattern that might help, please let me know!

Upvotes: 1

Views: 43

Answers (1)

deceze
deceze

Reputation: 522250

The way to do this would be to dependency inject a factory/DI container:

export default class Screen() {
   constructor(di) {
       this._di = di;
   }

   getPixels() {
       // Get pixels from a canvas
       return this._di.getInstance('pixels', [pixels]);
   }
}

However: don't overdo it. DI is useful and necessary, however that doesn't mean you need to "soft code" everything and keep everything configurable into infinity. If your class is defined to return instances of another closely related class, and there's no real need for dependency injection because neither class needs any sort of "configuration" or may be replaced entirely, then simply forgo it.

Upvotes: 1

Related Questions