Jeff
Jeff

Reputation: 12785

Can I use named and unnamed bindings together?

I have the situation where a class requires two instances of a particular injected - one general, and one more specialized (the general one can also be the specialized one, but not necessarily).

My instinct was to do something like:

Bind<IAmAThing>().To<AGeneralThing>();
Bind<IAmAThing>().To<ASpecializedThing>().Named("Special");

And then use a constructor like

MyClass(IAmAThing generalThing, [Named("Special")]IAmAThing specializedThing) {

But I'm not sure whether this is going to work and if it does, whether it will work consistently, or if there's another way of doing what I am thinking of. Essentially if I don't name an instance, can it fall back to the un-named instance? Is there a way of specifying a default like this?

Of course I can name both instances, but that seems like it's going to be a pain down the road when someone assumes they can just ask for an instance...

Upvotes: 1

Views: 274

Answers (2)

Radek Strugalski
Radek Strugalski

Reputation: 568

It looks like Niject accepts these 2 bindings but when calling Resolve<>() it throws an exception with complaints about having 2 or more bindings. The workaround I made is to have all bindings to the same interface have concrete name. Other problem is that when resolving a named binding, name does not propagate downstream, so it has to be also implemented manually. Not great.

Upvotes: 0

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

When you used named binding, the request must also have a name - and it must be an exact match. There's no fall back on an unnamed binding. Are you sure, that your design requires this? How is it relevant for the consumer of the interface which instance he gets injected? Seems complicated and seems it's hiding stuff...

Upvotes: 1

Related Questions