hmlongco / Resolver

Swift Ultralight Dependency Injection / Service Locator framework
MIT License
2.15k stars 190 forks source link

Re-registering doesn't work #144

Closed indieSoftware closed 2 years ago

indieSoftware commented 2 years ago

It seems it's not possible to re-register dependencies to overwrite previously registered instances.

I have tested it with version 1.4.5 and with 1.5.0 with the following XCTest code:

    class Service {
        var value: Int = 0
    }

    func testResolver() {
        let service1 = Service()
        Resolver.register { service1 as Service }
        service1.value = 1
        let service1Resolved = Resolver.resolve(Service.self)
        XCTAssertEqual(1, service1Resolved.value)

        let service2 = Service()
        Resolver.register { service2 as Service }
        let service2Resolved = Resolver.resolve(Service.self)
        XCTAssertEqual(0, service2Resolved.value)
    }

My use-case for that is as following: I'm writing a UnitTest to test a consumer class which relies on a service. So, I'm registering that service mock in the test method. During the test I'm modifying the mock to test my consumer class. Then I have a second test method which tests something different on that consumer class so I'm creating a new instance of that mock, re-registering it, creating a new consumer class and now the test fails because the newly created consumer class resolves the previously registered mock with it's changed state instead of the newly created fresh mock. When running the test methods manually one after the other then both tests passes, but when running the test suite only the first test method passes. The second test method fails because the mock has not the expected state.

So, when calling register with a new instance of a type a second time I would expect to get that second registered instance resolved, but still getting only the first registered instance.

indieSoftware commented 2 years ago

It seems it's not a problem of Resolver, but of my project's set up.

hmlongco commented 2 years ago

Was going to say that it shouldn't be a problem. There are actually unit tests for re-registration.

indieSoftware commented 2 years ago

Yes, it was because of the scope which has been changed, but your documentation clarified that: https://github.com/hmlongco/Resolver/blob/master/Documentation/Scopes.md