Would I benefit from implementing some kind of dependency injection? #3823
Replies: 1 comment 4 replies
-
Hi, MobX is all about automatically reacting to observable changes. It doesn’t force any architectural choices, which is why you are free to use any approach - whether it’s using singleton stores directly or using some kind of dependency injection. When it comes to DI there are 2 approaches:
class RootStore {
analyticsApi = new AnalyticsApi();
analyticsStore = new AnalyticsStore(this.analyticsApi);
userStore = new UserStore(this.analyticsStore);
} It’s simple because no libraries are required, but it might be tedious to specify all the dependencies.
Over time, I have gradually shifted from manual dependency injection to singletons, primarily because I don't need my stores to be shared among different apps. Writing unit tests without DI is not as simple, but since migrating to vitest, I can easily mock any module. If I ever need my store to be executed in different contexts, I would definitely choose to pass dependencies through a constructor or a callback to minimize coupling: userFormStore.submit(() => {
userListStore.reload();
}) I believe there are no golden rules. If the modules are tightly coupled, it can make the system more complex and harder to manage. But in some cases, especially when the modules need to communicate closely, a bit of coupling can actually simplify the design and make code more readable. It's all about finding the right balance and avoid the cargo cult. |
Beta Was this translation helpful? Give feedback.
-
So, I have a pretty large React Native codebase that's used in production and has been built over a number of years. The codebase follows the "root store" pattern and I have a number of classes and subclasses that make up the project's business logic.
I'm currently trying to make the individual classes re-usable in another project and have realized that I have a lot of internal dependencies that I probably could/should refactor in order to lessen som of this spaghetti:
The pattern I'm currently using is something like:
So as you can see, I'm pretty much injecting all stores everywhere. Now, I could of course refactor this a bit so that I only pass the stores that I actually need:
This, it seems to me, is a kind of very simple dependency injection pattern. What I'm trying to figure out is whether or not I would benefit from using a library to handle this, such as InjectionJS, TSyringe, InversifyJS or TypeDI. I guess I don't truly understand dependency injection well enough to be able to know what my needs are. When I look at the docs for the mentioned libraries, it's not obvious to me what benefit they add, but surely, since they exist, they solve some kind of problem in this space?
So - what are your thoughts given my structure? What should I do?
Beta Was this translation helpful? Give feedback.
All reactions