I posted this question to stack overflow (
http://stackoverflow.com/
questions/3677755/in-ninject-2-0-how-do-i-have-both-a-general-binding-
and-a-binding-for-a-specfic) and haven't gotten any responses, so I
thought I would try here.
I have a situation where I want to dependency inject my user object,
but also place the current user in the IoC container. I want the
following lines to work:
kernel.Get<User>(); // Should return a new User()
kernel.Get<User>("Current"); // Should return the current user
One might think bindings like this would work:
Bind<User>().ToSelf();
Bind<User>().ToMethod(LoadCurrentUser).InRequestScope().Named("Current");
Of course, that gives:
Ninject.ActivationException: Error activating User
More than one matching bindings are available.
Activation path:
1) Request for User
Suggestions:
1) Ensure that you have defined a binding for User only once.
I understand the error since a Named binding does not restrict the
application of that binding, so both bindings apply. It seems clear
that I need to use the contextual bind with the .When*() methods but I
can't come up with any way to do that. I feel like there should be
when methods that detect whether a named instance is applied.
Something like:
// Not valid Ninject syntax
Bind<User>().ToSelf().WhenUnnamedRequested();
Bind<User>().ToMethod(LoadCurrentUser).WhenNamedRequested().InRequestScope().Named("Current");
I can't find any place on the IRequest interface or it's properties
that tells me the name requested. How do I do this?