Acts like bind, but instead of binding to a specific type request, it gets bound to named
parameters with this name
.
Without bindings, named parameters will only be resolved if they don't have a default value.
If they have no default value, they will be resolved if they can, but will be set
to null
if the resolve fails.
to
will only be bound to parameters with a compatible type. Therefore, multiple bindings
can be made to the same name
. The value that will be injected is chosen based on the type
annotation of the parameter:
final c = bindName("x", to: 123)
.bindName("x", to: "string")
.bindName("x", to: SomeImplementation);
c.resolve(({y}) {
print(y); // null <-- nothing is bound to y, so attempt to make or else return null
});
c.resolve(({num x}) {
print(x); // 123 <-- bound int is assignable to num
});
c.resolve(({String x}) {
print(x); // "string" <-- bound String is assignable to String
});
c.resolve(({SomeClass x}) {
print(x); // Instance of 'SomeClass' <-- no binding is assignable, so attempt to make
});
c.resolve(({SomeClass x: defaultValue}) {
print(x); // defaultValue <-- no binding is assignable, so use default value
});
c.resolve(({SomeInterface x}) {
print(x); // Instance of 'SomeImplementation'
// ^-- bound SomeImplementation is assignable to SomeInterface
});
c.resolve(({x}) {
print(x); // 123 <-- everything is assignable to dynamic, so choose first binding
});
Source
IoCContainer bindName(String name, {to});