Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Class with multiple initializers defined with Container scope, creates multiple objects #527

Open
yapiskan opened this issue Jan 17, 2023 · 1 comment

Comments

@yapiskan
Copy link

Hey,

I am having a problem on my side whether I am not sure if this is an intended behavior from Swinject or not.

The case I am dealing with is, I have a class that I would like to be a singleton (container scope). This class has multiple initializers hence I have multiple registrations. My expectation is since the object scope is defined as container during the app lifecycle, it would return the same instance. However, my observation is that a new object is created per initializer which doesn't make a lot of sense.

A sample would look like below;

class Animal {
    private var name: String?
    private var age: Int?
    
    init() {
        
    }
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    init(name: String) {
        self.name = name
    }
    
    init(age: Int) {
        self.age = age
    }
}

...

container.register(Animal.self) { _, name in
    Animal(name: name)
}.inObjectScope(.container)

container.register(Animal.self) { _, age in
    Animal(age: age)
}.inObjectScope(.container)

container.register(Animal.self) { _ in
    Animal()
}.inObjectScope(.container)

container.register(Animal.self) { _, name, age in
    Animal(name: name, age: age)
}.inObjectScope(.container)

let a1 = container.resolve(Animal.self, argument: "Test") // object 1
let a2 = container.resolve(Animal.self, argument: 10) // object 2
let a3 = container.resolve(Animal.self) // object 3
let a4 = container.resolve(Animal.self, argument: "Test1") // object 1
let a5 = container.resolve(Animal.self, arguments: "Test1", 11) // object 4
let a6 = container.resolve(Animal.self, arguments: "Test", 10) // object 4

My expectation for above is that, it would be only a single object created per app lifecycle.

Anything that helps me understand why it behaves like this, is appreciated!

@skorulis
Copy link

skorulis commented Nov 2, 2023

The storage of the instance is tied to the registration not the type which is why you don't always get the same Animal.
This also means that registrations with arguments don't work as expected since the storage key does not take into account the value of the argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants