0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michael Crook
  • 1,520
  • 2
  • 14
  • 37

1 Answers1

1

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!

Nate Diamond
  • 5,525
  • 2
  • 31
  • 57
  • I don't think that is really correct.. All it is doing is turning my IOC container into a singleton... Just to clarify, I am attempting to make it so that I can Register a List of Interfaces into my IOC container and then dynamically assign what type of class is inside of the List (that implements the interface) – Michael Crook Mar 27 '14 at 01:16
  • That's what your IOC is, to an extent. It's static access to 'singleton' ViewModels and controllers, declared via portable interfaces. You do get [some benefits](http://stackoverflow.com/questions/1328263/singleton-vs-servicelocator) for doing this, such as simpler centralized configuration, lifetime management, better testability, lower coupling, separation of concerns, etc. – Nate Diamond Mar 27 '14 at 16:55
  • I was just trying to use my IOC container to initilize all List's with the interface I specified given a specific implimentation.. From the look of it the main way your supposed to use IoC is Interface -> implementation not Container -> Container – Michael Crook Mar 27 '14 at 23:26
  • Well, you can have the IOC create the container whenever, you just have to have your app inject the contents at runtime. `ViewModelLocator.MyInterfaces.Add(myExampleObject);` – Nate Diamond Mar 28 '14 at 00:00