Swinject: Resolving dependencies with protocol arguments

Created on 20 Oct 2016  Â·  1Comment  Â·  Source: Swinject/Swinject

Hello,

It is possible to do something like this, where the argument passed to the dependency container when trying to resolve a dependency is typed as a protocol?

protocol ArgumentType {}
struct Dependency {}

let container = Container()
container.register(Dependency.self) { (container: ResolverType, argument: ArgumentType) in
  return Dependency()
}

extension String: ArgumentType {}

let dependency = container.resolve(Dependency.self, argument: "I’m the argument!")

This fails to find the registered dependency, this way. If I change the registration to specify String as the argument type, instead of ArgumentType:

container.register(Dependency.self) { (container: ResolverType, argument: String) in
  return Dependency()
}

Then it resolves as expected.

Please advise – thank you!

Most helpful comment

OK, figured it out. This works so long as you do:

let dependency = container.resolve(Dependency.self, argument: "I’m the argument!" as ArgumentType)

>All comments

OK, figured it out. This works so long as you do:

let dependency = container.resolve(Dependency.self, argument: "I’m the argument!" as ArgumentType)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

igorkotkovets picture igorkotkovets  Â·  7Comments

irace picture irace  Â·  5Comments

grzegorzkrukowski picture grzegorzkrukowski  Â·  7Comments

Mijail picture Mijail  Â·  6Comments

igorkotkovets picture igorkotkovets  Â·  7Comments