views:

94

answers:

2

I have a ViewModel, it takes two parameters in the constructor that are of the same type:

public class CustomerComparerViewModel
{
    public CustomerComparerViewModel(CustomerViewModel customerViewModel1,
                                     CustomerViewModel customerViewModel2)
    {

    }
}

public class CustomerViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

If I wasn't using IOC I could just new up the viewmodel and pass the sub-viewmodels in. I could package the two viewmodels into one class and pass that into the constructor but if I had another viewmodel that only needed one CustomerViewModel I would need to pass in something that the viewmodel does not need.

How do I go about dealing with this using IOC? I'm using Ninject btw.

Thanks

+1  A: 

I'm not familiar with Ninject, but it would seem to me that in order for the IoC to know what CustomerViewModels to Inject into your constructor you would have to setup these objects in advance. Using MEF like attributes and Psuedo code it might look something like...

[Export()]
public class CustomerSelectorViewModel
{
    [Export("CustomerA")]
    public class CustomerViewModel FirstSelection {get;set;}

    [Export("CustomerB")]
    public class CustomerViewModel SecondSelection {get;set;} 
}

[Export()]
public class CustomerComparerViewModel
{
    [ImportingConstructor]
    public CustomerComparerViewModel([Import("CustomerA")]CustomerViewModel customerViewModel1, [Import("CustomerB")]CustomerViewModel customerViewModel2)
    {

    }
}
Agies
A: 

Here's how to do it in Ninject:

Container.Bind<CustomerViewModel>().ToSelf().WhenTargetHas<CustomerA>();
Container.Bind<CustomerViewModel>().ToSelf().WhenTargetHas<CustomerB>();

Then in the constructor of the class you are using them in:

public class CustomerComparerViewModel
{
    public CustomerComparerViewModel([CustomerA]CustomerViewModel customerA,
                                     [CustomerB]CustomerViewModel customerB)
    {

    }
}
Lee Treveil