Reputation: 16119
I have a class with a property of type ICollection<object>
that I'm trying to inject with an instance of type ObservableCollection<object>
. If I obtain an instance via Get<>
Ninject gives me the correct type, but if I get it to inject it into a class it creates a List<object>
instead. Can anyone explain to me what's going on?
using Ninject;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace NinjectTest
{
class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel();
kernel.Bind<MyClass>().ToSelf();
kernel.Bind<ICollection<object>>().To(typeof(ObservableCollection<object>));
ICollection<object> foo = kernel.Get<ICollection<object>>();
ICollection<object> bar = kernel.Get<MyClass>().Collection;
Debug.Assert(foo is ObservableCollection<object>); // ok
Debug.Assert(bar is ObservableCollection<object>); // fails
}
}
public class MyClass
{
[Inject] public ICollection<object> Collection { get; set; }
}
}
Upvotes: 0
Views: 62
Reputation: 13233
This is per the "Multi Injection" feature.
When you try to inject an array []
, an IEnumerable<T>
, an ICollection<T>
or an IList<T>
it is always interpreted as GetAll<T>
- so it will create an instance of each binding for T
and return it as the "collection" type you've requested.
So far what i've done is create specific interfaces like:
public interface IFooCollection : ICollection<Foo>
and then ctor-inject an IFooCollection
. This way you work around the multi injection feature.
Of course you could also create an interface for the observable collection:
public interface IObservableCollection<T> : ICollection<T>, INotifyCollectionChanged
Upvotes: 2