Search code examples
c#dependency-injectionmvvm-lightsimpleioc

mvvm light simpleIoc constructor injection


i want to inject a list to my viewmodel constructor with the ServiceLocator

my viewmodel:

public class ShowEmployeeViewModel: ViewModelBase
{
    private IList<IEmployee> _empl;

    public ShowEmployeeViewModel(IList<IEmployee> emp)
    {

        this._empl = emp;

        _empl.Add(new Employee() { empName = "foo", enpFunction = "bar" });
    }
}

my servicelocator:

public class ViewModelLocator
{

    public ViewModelLocator()
    {

        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        //register the interface against the class

        SimpleIoc.Default.Register < IList < IEmployee >, List <Employee>>();


        SimpleIoc.Default.Register<ShowEmployeeViewModel>();

    }

    public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
    public ShowEmployeeViewModel ShowEmployee
    {
        get
        {
            return ServiceLocator.Current.GetInstance<ShowEmployeeViewModel>();
        }
    }

when i run this code i got an error: "Cannot register: Multiple constructors found in List`1 but none marked with PreferredConstructor." PS: i only got this error when i try to registre a list "IList" but when i register my interface like this:

SimpleIoc.Default.Register < IEmployee , Employee >();

it works fine, any idea how to register a list? thanks in advance


Solution

  • Don't map the IList interface, use a factory for your ShowEmployeeViewModel class:

    SimpleIoc.Default.Register(() => new ShowEmployeeViewModel(new List<IEmployee>()));