8000 Class with multiple initializers defined with Container scope, creates multiple objects · Issue #527 · Swinject/Swinject · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Class with multiple initializers defined with Container scope, creates multiple objects #527
Open
@yapiskan

Description

@yapiskan

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0