Question

Is it possible to use dependency injection in MVVM light on a List of Interfaces?

I've tried having the dependency be List<IMyInterface> IList<IMyInterface>. From within the ViewModelLocator I have then also tried both with and without the List<>. If I do it without List<> I get a cache doesn't have a value for List exception, if I do it with, (for List) I get a no preferred constructor exception (as List has multiple constructors, and I can't set the attribute as it is a class inside of .net)

The only possible solution I can think of will limit my testability, which would be to have all the lists as concrete implementations, i.e. I have

List<dataType> data = new List<dataType>();

Is there a way to IOC a list? or are you supposed to concrete code?

Was it helpful?

Solution

ViewModelLocator can have static objects that are accessible through it.

public class ViewModelLocator
{
    ....
    private static List<IMyInterface> _myInterfaces;
    public static List<IMyInterface> MyInterfaces
    {
        get
        {
            return _myInterfaces;
        }
        set
        {
            // So that it will be readonly. Technically unnecessary, but may be good
            // practice.
            if(_myInterfaces != null) return;
            _myInterfaces = value;
        }
    }
}

Then in your main app wherever you get your list,

ViewModelLocator.MyInterfaces = GetMyInterfaceList();

Hope this helps and Happy Coding!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top