How do I enter dependencies in the collection form?
How to connect dependencies in which the dependency is in the form of a collection?
Example:
public class Ninja {
public List<IShuriken> Shurikens {get;set;}
public IKatana Katana {get;set;}
public void Attack()
{
// some code goes here to use weapons and kill people
}
}
How do I use a container like Ninject in this case?
EDIT: I'm not talking specifically about Ninject, but I'm using DI / IOC. :)
a source to share
You can Bind
close the type List<X>
ToConstant()
, ToMethod()
etc.
But you will need to provide more details on what you want on the list, or I will just do some idle thinking about what you want.
EDIT in response to your comment and your comment: If you are dealing with 'Unknown' or free dependencies, then MEF does a lot of things in that direction.
[In general with DI] If you are doing something internally and this is a more "famous" / fixed / complex resolution mechanism, you are better off simulating something like this by having a repository or other coordinating object that will manage the list you can query for subsets and / or other projections as needed.
[If you are interested in specific mechanisms in Niject], you would go crazy with downloading the source and do grep / FIF / Shift-Ctrl-Q List
to tell the real story - the code is clean and tidy, and the test examples are examples.
For example, you can bind multiple elements to the interface and then add them to the collection automatically: -
namespace Ninject.Tests.Integration.EnumerableDependenciesTests {
public class WhenServiceRequestsUnconstrainedListOfDependencies
{
[Fact]
public void ServiceIsInjectedWithListOfAllAvailableDependencies()
{
kernel.Bind<IParent>().To<RequestsList>();
kernel.Bind<IChild>().To<ChildA>();
kernel.Bind<IChild>().To<ChildB>();
var parent = kernel.Get<IParent>();
VerifyInjection( parent );
}
protected override void VerifyInjection( IParent parent )
{
parent.ShouldNotBeNull();
parent.Children.ShouldNotBeNull();
parent.Children.Count.ShouldBe( 2 );
parent.Children[0].ShouldBeInstanceOf<ChildA>();
parent.Children[1].ShouldBeInstanceOf<ChildB>();
}
}
public class RequestsList : IParent
{
public IList<IChild> Children { get; private set; }
public RequestsList( List<IChild> children )
{
Children = children;
}
}
public interface IChild { }
public class ChildA : IChild { }
public class ChildB : IChild { }
public interface IParent
{
IList<IChild> Children { get; }
}
}
a source to share
I don't know about Ninject. in Castle Windsor , you would use ListResolver
and provide all implementations IShuriken
.
a source to share