hmlongco / Factory

A new approach to Container-Based Dependency Injection for Swift and SwiftUI.
MIT License
1.71k stars 107 forks source link

Question about singleton scope in shared container #92

Closed IvanShah closed 1 year ago

IvanShah commented 1 year ago

Hi there, I have updated on version 2.1.1 and still facing problem from https://github.com/hmlongco/Factory/issues/86 if I have my singleton service in SharedConatiner and it used in other services and containers and it injects somewhere else in my code - service initing twice. First time when it inits for other service, second time when injects. For all my containers I use manager.defaultScope = .singleton. Could you please explain how to fix that? And I have another question. How can I setup default scope for SharedConatiner services?

hmlongco commented 1 year ago

Yep. That's a fairly specific bug in regard to singletons in SharedContainer being resolved across multiple container instances and multiple container classes. I'll look into it.

At this point in time defaultScope is container-based. Any resolution from a container uses that container's default scope.

Your best bet there is simply to mark the service with .singleton.

IvanShah commented 1 year ago

I tried add .singleton to service in SharedContainer but it still inits twice. Behaviour stayed the same.

hmlongco commented 1 year ago

As mentioned this is a bug.

The "Your best bet there is simply to mark the service with .singleton." is the answer to the second question you asked. Since "SharedContainer" is virtual, there's no associated defaultScope, so each definition would need to marked as singleton.

That approach, however, won't work until the bug is fixed for this specific use case.

hmlongco commented 1 year ago

It's not an official release yet, but you can pull the main branch and see if this corrects the problem.

IvanShah commented 1 year ago

Yes, it's helped, service init one time thank you