Swinject / SwinjectAutoregistration

Swinject extension to automatically register your services
MIT License
251 stars 45 forks source link

How to auto register when init has default arguments? #70

Closed tfalves closed 3 years ago

tfalves commented 3 years ago

Is it possible to specify how to resolve a class with a constructor that has a default argument? Take the following example

init(argument1: Foo, argument2: Bar = Bar())
{
    ...
}

Registering it without specifying the constructor will fail during runtime, as the resolver does not assume the default argument, hence, does not recognize the registry

container.autoregister(MyClass.self, initializer: MyClass.init)

//This will fail
container.resolve(Myclass.Self, argument: Foo())

Registering it specifying a constructor will not work, as it will fail during compile time, as it cannot recognize an init that has only 1 argument

container.autoregister(MyClass.self, initializer: MyClass.init(argument1:))

The only way I could think of, to resolve this issue, is to explicitly create a convenience init that takes argument1 and internally invokes the intended init, passing argument2 with the intended default value.

convenience init(argument1: Foo)
{
    self.init(argument1: argument1, argument2: Bar())
}

init(argument1: Foo, argument2: Bar = Bar())
{
    ...
}

Is there any other way to achieve this?

tkohout commented 3 years ago

We can only get the types of the arguments but not the default value from the initializer.

You can either use a dedicated convenience init or use pure Swinject registration code.