Search code examples
mvvmmvvm-lightviewmodellocator

How to Register Multiple Interface Implementation In IoC in MvvmLight?


Register Multiple Interface Implementation In LightInject IoC

How to use MvvmLight's Ioc to solve the problem? I have multiple DataService (DataService1, DataService2, DataService3 ...). They are all IDataService and need to be contacted with multiple ViewModel. Mvvmlight can't do it:

SimpleIoc.Default.Register<IDataService, DataService1>("DataService1Key");
SimpleIoc.Default.Register<IDataService, DataService2>("DataService2Key");
...

Solution

  • You can also use 'class' key identifiers in MvvmLight, like so

    Class1 c1 = new Class1();
    Class2 c2 = new Class2();
    
    SimpleIoc.Default.Register<IDataClass>(() => c1, "Class1");
    SimpleIoc.Default.Register<IDataClass>(() => c2, "Class2");
    
    var t = SimpleIoc.Default.GetInstance<IDataClass>("Class1");
    var s = SimpleIoc.Default.GetInstance<IDataClass>("Class2");