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()
?– Maniero
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...
– Luiz Felipe