views:

44

answers:

1

Right then, I've run into a situation using Unity that I don't know how to solve/approach...Here's my problem.

I'm developing a WPF application and I'm using MVVM (Prism Implimentation hence the Unity container). I have a ViewModel called MenuItemsViewModel (plural) which contains an IEnumerable of MenuItemViewModel (singular). In the constructor of the MenuItemsViewModel I'm populating this collection from a generator function like this...

    yield return new MenuItemViewModel(eventAggregator)
    {
        Text = "Dashboard",
        CommandText = "DASHBOARD"      
    };
    yield return new MenuItemViewModel(eventAggregator)
    {
        Text = "Areas",
        CommandText = "AREAS"
    };
    yield return new MenuItemViewModel(eventAggregator)
    {
        Text = "Users",
        CommandText = "USERS"
    };  //etc....

I don't really want to be doing this but rather relying on the container to construct these objects for me but how in Gods name do I go about that? I don't really want my Items ViewModel to have any knowledge of my Item ViewModel other than the interface it implements but I've got about 15 of these menu items, each with different property values.

I'm not completely new to DI/IoC but this is a big question for me. I see and have benefited from having my services injected but what do you do about concrete values?

Am I think totally in the wrong terms here? Should I be just resolving the concrete instance from the container and then setting the properties? That would be an option but I like my props to be readonly if possible.

I hope this is clear enough,..shout at me if not :-)

Any help is much appreciated.

+1  A: 

I would use resolved arrays to inject menu items:

container
  .RegisterInstance("DASHBOARD", new MenuItemViewModel(...))
  .RegisterInstance("AREAS", new MenuItemViewModel(...))

  .RegisterType<MenuItemsViewModel>(
     new InjectionConstructor(new ResolvedArrayParameter<MenuItemViewModel>()))
onof
Actually, if MenuItemsViewModel has a constructor that takes a MenuItemViewModel[] (has to be an array) then the default dependency resolution should kick in and will automatically inject all the named instances of MenuItemViewModel for you.
Chris Tavares
@Chris you're right +1
onof
Genius,...genius! Thanks very much :-)
Stimul8d