ivlevAstef / DITranquillity

Dependency injection for iOS (Swift)
MIT License
423 stars 32 forks source link

Resolve with parameter #153

Closed sssbohdan closed 4 years ago

sssbohdan commented 4 years ago

I'm sorry if it was asked before, but I couldn't find it. I have an object with a constructor that takes 1 parameter. Code:

container
.register { mediaType in UploadMediaViewModel(mediaType: mediaType) }
.lifetime(.prototype)

How can I resolve it in runtime using mediaType? Because obviously justself.container.resolve() will result into crash. Thanks.

ivlevAstef commented 4 years ago

Hello. This functionality is not described, because it is unsafe and contradicts the principles of DI containers.

But your can write:

container.register { mediaType in UploadMediaViewModel(mediaType: arg(mediaType)) }

And before resolve to pass a parameter:

container.extensions(for: UploadMediaViewModel.self)?.setArgs(yourMediaType)
let object = container.resolve()

Or your can use Provider:

let object = (container.resolve() as Provider<UploadMediaViewModel, MediaType>).value

P.S. Add ViewModel into DI container this is a mistake. DI container needs only for Dependency and Classes, not models.

sssbohdan commented 4 years ago

I don't get why property injection contradicts with principles of DI containers either why it's bad to put ViewModel in the container. But thanks you for your help :)