Swinject / SwinjectAutoregistration

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

Possible Limitation of SwinjectAutoregistration Involving Initializers #51

Closed vermont42 closed 4 years ago

vermont42 commented 5 years ago

Am I correct that, when I use SwinjectAutoregistration, no component initializer may be private?

In my app, I have a service/protocol, GameCenterable, with two components that implement that protocol, RealGameCenter and TestGameCenter. RealGameCenter has a private initializer, which takes no arguments. TestGameCenter has an internal initializer which takes a Bool argument, isAuthenticated. For context, I show in the snippets below registration and use of TestGameCenter and RealGameCenter. To make the latter work, I had to change the initializer of RealGameCenter from private to internal.

Vanilla Swinject does not have this limitation, but I would prefer to use SwinjectAutoregistration so I don't get Optionals from the container.

// registration and use of TestGameCenter component
container.autoregister(
  GameCenterable.self,
  argument: Bool.self,
  initializer: TestGameCenter.init(isAuthenticated:)
)

let gameCenter = container ~> (GameCenterable.self, argument: false)

// registration and use of RealGameCenter component
container.autoregister(
  GameCenterable.self,
  initializer: RealGameCenter.init
)

let gameCenter = container ~> (GameCenterable.self)
jakubvano commented 5 years ago

AFAIK there is nothing special about SwinjectAutoregistration with regard to the access modifiers. If .init is private, you cannot reference it from other source file - shouldn't matter in what context. What puzzles me though, is that vanilla register works 🤔 Is your injection code in the same sourcefile as the definition of RealGameCenter.init? Could it be that RealGameCenter has more that one init? Can you reproduce this behavior in isolated example?

vermont42 commented 4 years ago

Thanks, @jakubvano.

Looking at the code now, I see that I had to comment out the line making RealGameCenter's initializer private, even for vanilla register. My observation was incorrect.

Makes sense that a private initializer would be problematic for Swinject.

In my conference talk and blog post, in the section on Swinject, I plan to mention, as a positive of Swinject, the help that you and other Swinject contributors provided.