hmlongco / Resolver

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

How to force resolve again with @Injected annotation? #97

Closed haemi closed 3 years ago

haemi commented 3 years ago

I have a static property, let's say

struct Foo { // Singleton!
    @Injected static var bar: Bar
}

Now when I run unit tests, I would like to inject a different object in the different unit tests, like

func test1() {
    let mocks = Resolver(parent: Resolver.main)
    let barMock = Bar(bar: "hello")
    mocks.register {
        barMock
    }
    Resolver.root = mocks

    // do tests

    // reset
    Resolver.root = Resolver.main  
}

func test2() {
    let mocks = Resolver(parent: Resolver.main)
    let barMock = Bar(bar: "world")
    mocks.register {
        barMock
    }
    Resolver.root = mocks

    // do tests

    // reset
    Resolver.root = Resolver.main  
}

My problem is that the first mock (with hello) stays and the @Injected static var bar: Bar part does not get resolved again... Is there a way to solve this?

hmlongco commented 3 years ago

I'd never considered using @Injected on a static class variable. But since static vars are only instantiated once, your only option would be to simply reassign it.

// setup
Foo.bar = Resolver.resolve(Bar.self)
// tests
haemi commented 3 years ago

that works, thanks a lot!