Reputation: 60466
i got the tiny interface ITest:
public interface ITest
{
void DoSomething();
}
and some implementations of ITest
public class Test : ITest
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
public class Test2 : ITest
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
public class Test3 : ITest
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
public class Test4 : ITest
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
Now i setting up Ninject:
kernel.Bind<ITest>().To<Test>().Named("Test");
kernel.Bind<ITest>().To<Test2>().Named("Test");
kernel.Bind<ITest>().To<Test3>().Named("Test");
kernel.Bind<ITest>().To<Test4>().Named("Test");
And here is my first Problem.
If iam trying to get an instance using
ITest test = kernel.Get<ITest>("Test");
it results in a exception "Error activating ITest More than one matching bindings are available. ...". The documentation says: "Gets an instance of the specified service by using the first binding with the specified name."
Second Problem:
List<ITest> servicesList = new List<ITest>(kernel.GetAll<ITest>("Test"));
results in a exception "Error activating string No matching bindings are available, and the type is not self-bindable. ...". The documentation says: "Gets all instances of the specified service using bindings registered with the specified name."
Any ideas ? Thanks in advance!
Upvotes: 2
Views: 1923
Reputation: 1038810
You are giving all your instances the same name Test
so it's normal that this would be ambiguous. Give them different names when registering your kernel:
kernel.Bind<ITest>().To<Test>().Named("Test1");
kernel.Bind<ITest>().To<Test2>().Named("Test2");
kernel.Bind<ITest>().To<Test3>().Named("Test3");
kernel.Bind<ITest>().To<Test4>().Named("Test4");
Now you can fetch your instances by name:
ITest test = kernel.Get<ITest>("Test3");
And to get them all you no longer need a name:
List<ITest> servicesList = kernel.GetAll<ITest>().ToList();
Upvotes: 4