Meraki-Solutions / green-state

Composable state management for Javascript apps with first-class IoC support
https://meraki-solutions.github.io/green-state/
MIT License
1 stars 1 forks source link

Refactor container to never register anything in parent containers #5

Closed benglass closed 4 years ago

benglass commented 4 years ago

We have determined this causes unwanted side effects more often than not that are very difficult to troubleshoot. Previously we had assume the main problem is that NeedsFoo could miss Foo that was in the child container and so we only handled the problem of ensuring that we register in the deepest container of any dependency.

However we determined that we commonly have unwanted side effects that happen when services requested in child containers are auto-registered in parent containers.

The prime example of this type of problem is stateful services.

Example:

If instead we ensure that we never automatically create instances in the root container and we dispose of the child container the map is unmounted, we will automatically garbage collect the LoadingState instance and not have this issue.

If we really wanted to ensure that a specific service gets created in the root container, we can be explicit and register or autoRegister it there. This is comparatively rare and an advanced use case that isn't that hard to achieve. Conversely, as illustrated by the example above, the default behavior of auto registering services in the root container can cause subtle bugs that are difficult to reason about and solve.

If you tried to pre-emptively register in the child container all the dependencies of Map that are stateful, you quickly find yourself in whack-a-mole territory where you have to think about this every time you create a service and remember to update your registration code.