hmlongco / Factory

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

Overriding registration in preview #132

Closed hyazel closed 1 year ago

hyazel commented 1 year ago

Hello,

I register a service like this :

var collectionService: Factory<CollectionServiceContract> {
        self { CollectionService() }
            .onPreview {
                CollectionServiceMock(items: collectionMock1)
            }
    }

My purpose is to have a CollectionServiceMock for previews that use collectionMock1 in most of my views.

But sometimes I'd like to use an another mock than collectionMock1.

In my preview I tried to do something like this :

 static var previews: some View {
        _ = ServiceContainer.shared.collectionService.register { CollectionServiceMock(items: collectionMock2) }

       return MyView()
}

But doesn't seem to use the collectionMock2 instead of the collectionMock1.

My question is : How do you switch your mock during previews ?

hmlongco commented 1 year ago

See the section "The Factory Wins" in the documentation on Factory Modifiers.

https://hmlongco.github.io/Factory/documentation/factory/modifiers

hyazel commented 1 year ago

Thanks !

hyazel commented 1 year ago

It seems that using once() modifier would solve what I want to achieve.

Is there a danger or a side effect I don't see, using the once() modifier on all my services (which are not singleton like the example in the once() documentation) for my previews ?

hmlongco commented 1 year ago

Once just adds a small bit of processing to the resolution process, so you can use it as much as you like. That said, I'd only use it for scenarios where you're trying to override one of the contexts and you put those context modifiers inside of the Factory. It makes no sense to have it for plain or scoped factories.

Don't forget the auto registering option.