0

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

mm8
  • 163,881
  • 10
  • 57
  • 88
Arh Hokagi
  • 170
  • 5
  • 21
  • 2
    You are mixing things up here. A DI Container (and DI in general) is not meant to build up DTOs and entities; its meant to build up graphs of application components, i.e. the classes that contain that application's behavior. `ShowEmployeeViewModel` is a DTO and `IEmployee` is an entity. Do not register them in your container. – Steven Feb 19 '17 at 21:18

1 Answers1

1

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

SimpleIoc.Default.Register(() => new ShowEmployeeViewModel(new List<IEmployee>()));
mm8
  • 163,881
  • 10
  • 57
  • 88
  • it works, but wouldn't that defeat the purpose of the Dependency Injection, how can i register a type against its interface? thanks – Arh Hokagi Feb 19 '17 at 20:49
  • You don't map a generic list against a specific type. This makes no sense since you want to be able to use a generic list for many different types. You could map a view model interface, e.g. IShowViewModel, against a concrete view model type though but that's another story and since your ShowEmployeeViewModel class doesn't even implement an interface it is not applicable here. – mm8 Feb 19 '17 at 20:51