10

I realize constructor injection is preferred but I'm curious how to use Ninject's contextual 'Named Bindings' when using another form of injection.

Specifically how do I do the following when using DependencyResolver or property injection.

public MyService([Named("Alpha")] IRepository repository)
{
    this.repository = repository;
}
Mark
  • 21,067
  • 14
  • 53
  • 71

1 Answers1

21

You can create a named binding to work on Alpha:

Bind<IRepository>().To<AlphaRepository>().Named("Alpha");

then you can specify others like:

Bind<IRepository>().To<AnotherRepository>().Named("Beta");

When your example constructor is used you will get the AlphaRepository.

In order to use the name with a property give the property a name attribute just like you you did for the param:

[Inject, Named("Alpha")]
public IRepository Foo {get; set;}
Mark
  • 21,067
  • 14
  • 53
  • 71
ryber
  • 4,537
  • 2
  • 26
  • 50
  • I know how to create the named binding and I know how to use the binding with a constructor. My question is how do I use a named binding when doing injection via property injection. – Mark May 30 '11 at 04:06
  • Updated to answer your question – ryber Jun 10 '11 at 19:05