Simple question

Topics: UI Architecture, Bootstrappers & IoC
May 12, 2011 at 3:10 PM
There is one chapter in documentation -
    protected override void OnInitialize() {
        Enumerable.Range(1, NumberOfTabs).Apply(x => {
            var tab = createTab();
            tab.DisplayName = "Item " + x;

My question is: why use createTab() "instead of" new TabViewModel()?
May 12, 2011 at 3:22 PM

The function can be used to customize both your view-model or properties of the view-model itself; I consider that part of a 'pull' composition approach, where the view-model retrieves needed objects from one of its dependencies.

May 12, 2011 at 3:23 PM

The createTab delegate is a factory method that the container inject into the constructor of the class:

public PageTwoViewModel(Func<TabViewModel> createTab) { ... }

Doing so allows you to let the container create each instance of TabViewModel (which in turn may have some dependencies to be satisfied) but WITHOUT having to esplicitly mention or reference the container in your code.

May 12, 2011 at 8:52 PM

I understand that we could use:



IoC.GetInstance(type, null)

to get instance of particular view model but it's still unclear to me why it is introduced in the constructor.
May 12, 2011 at 9:09 PM

Using IoC.Get inside your application code is considered an anti-pattern for at least two reasons off the top of my head: It's hard(er) to test the class that uses this and more importantly it obscures the true dependencies of the class that uses it. Also, it forces you to take a dependency on the IoC container directly (so I guess that's three). Using the func allows the class to declare it's dependencies very clearly. In effect it says "I need the ability to create instances of this type" The container can provide a factory when it instantiates the class. This also makes testing nice, because you can provide your own fake lambda as well.

May 12, 2011 at 9:37 PM

OK that's clear now.

We could also use interface - ITableViewModel - and some reflection helper methods to instantiate object (for example first class that implements this interface) and for test we could use some kind of mocking to replace "real" object with fake one.