Injection of dependencies into functions and not classes. Is it "wrong"?

Asked

Viewed 147 times

4

It is not new that the concept of dependency injection is almost directly related to classes. Tell me "dependency injection" and I can imagine the following:

// services/UserService.ts

export default class UserService {
  constructor(
    private manager: DatabaseManager
  ) {}

  async createUser(username: string, password: string): User {
    const user = new User();
    user.username = username;
    user.password = password;

    await this.manager.save(user);
    return user;
  }
}

Now I wonder if these same concepts can be applied in a function without harming the functional "style".

I thought of implementing my own container use it in a similar way to React Hooks:

// services/create-user.ts

export default async function createUser(username: string, password: string): User {
  const [manager] = useContainer([DatabaseManager]);

  const user = new User();
  user.username = username;
  user.password = password;

  await manager.save(user);
  return user;
}

I know I can implement this and it will work. The purpose of this question is to know if I will be hurting some principle of dependency injection (or of the functions themselves) in doing so. It would be a mistake to do that?

  • What is this useContainer()?

  • It would be a function whose goal would be to retrieve something from the Ioc container. I later edit the question to make this clearer...

1 answer

3


For me the way you want to do it is dependency injection done right. What I don’t like is strutting to do something simple. Creating parameter in function or field in class with the sole purpose of having dependency flexibility seems very wrong to me.

In many cases it should not even have the flexibility, even where it should have, it should be transparent for the application.

I don’t really know how this mechanism used in the question works, but to me it seems correct, even if it doesn’t follow the DI philosophy (I don’t cling to rules, I cling to solutions) you create a way to get the information you need the time you need, If this form is flexible or is not her problem and not its use there (decoupling), I would do so and never of what many people do creating cost for the object. Unless you have a larger goal of having a control over the class, but that doesn’t seem to be the case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.