hmlongco / Resolver

Swift Ultralight Dependency Injection / Service Locator framework
MIT License
2.14k stars 187 forks source link

@Injected vars not working after calling Resolver.reset() #159

Closed yosi199 closed 2 years ago

yosi199 commented 2 years ago

Hi, first let me say I really enjoy this library. Was thinking of writing my own but once I found out about Resolver I'm now using it.

One thing I'm trying to achieve in my SwiftUI app is clearing out all data after a user logs out. I'm using Resolver.reset() in order to clean all the dependency graph.

Right after I reset the graph, I navigate back to previous screen (login) and resolve all the dependencies I need, inline so that the user can login again. Something like this:

func onLogin() {
let authRepo: AuthRepository = Resolver.resolve
authRepo.login()
}

This works great and I'm able to relogin into the next screen. Here is where the problem - this next screen has a @StateObject viewmodel that get's all it's dependencies using the @Injected property wrappers and once the user performs an action that uses one of these dependencies - nothing happens. It won't crash, but also won't do the things I expect. Weird behaviour.

I'm sure I'm doing something wrong or don't understand the concept of resetting the graph. All depdendencies are .cached

Any idea what i'm doing wrong?

hmlongco commented 2 years ago

The 'graph' happens on a resolution where A depends on B which depends on C which depends on D.

Calling Resolver.reset should not be done. You basically lose all your registrations and they need to be recreated.

If you navigate to a new screen and not seeing inject happen correctly you might be seeing: https://stackoverflow.com/questions/60129552/swiftui-navigationlink-memory-leak/71829180#71829180

Finally, you might consider using my newer DI framework, https://github.com/hmlongco/Factory

Note there's a couple of examples in the Factory readme on session state.