levibostian / ExpressjsBlanky

Blank Express.js project to get up and running FAST.
MIT License
7 stars 0 forks source link

Impove dependency injection #46

Open levibostian opened 3 years ago

levibostian commented 3 years ago

I am doing manual dependency injection right now. This works, but I believe it could be better.

Requirements

What if you have a typo in the Dependency.UserController? You get a runtime exception. I would rather do:

let userController = container.userController()

And this returns back UserController. No runtime exceptions.

Ideas

The manual dependency injection I do right now takes care of a lot of the requirements above. However, the type checking on it is a mess. This code speaks for itself:

  inject<T>(dependency: Dependency): T {
    const overridenValue = this.overrides[dependency] as T
    if (overridenValue) {
      return overridenValue
    }

    switch (dependency) {
      case Dependency.KeyValueStorage:
        return (new RedisKeyValueStorage(this.inject(Dependency.RedisClient)) as unknown) as T
  1. I could simply refactor the existing manual dependency injection code to make it have strict type checking and not be a pain to type.

  2. Using a project like this for inspiration. Using this project does not allow you to use constructor injection but it does do lazy injection as well as includes various ways of doing injection which I could use to give me ideas on how to do this.


Overall, I am happy with what I have now but I still have some pains with (1) maintaining it especially as the code base grows and (2) it's not strictly type checked.