3

How can I inject my CustomerRepository into my CustomerVM view model? In my view, a WPF Page I have:

<Page.DataContext>
    <viewModel:CustomerVM/>
</Page.DataContext>

But my view model constructor obviously has parameter passed in,

    public CustomerVM(ICustomerRepository customerRepository)
    {
        //this._customerRepository = customerRepository;
    }

I get

Type 'CustomerVM' is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.

Really struggling to heck.

Any help appreciated.

CheGuevarasBeret
  • 1,364
  • 2
  • 14
  • 33
  • Can you give us the ling that gives you this error? or a snippet of the code ? – Danpe Oct 25 '12 at 19:27
  • Please see [Here][1] I recommend the Viewmodel locator approach [1]: http://stackoverflow.com/questions/5830199/setting-viewmodels-property-from-xaml – sayed saad Oct 25 '12 at 19:36

1 Answers1

1

I don't think you can initialize the DataContext within the XAML if you're using dependency injection. Set the DataContext in the code-behind for the view so Unity can resolve the dependencies. Try adding this to YourView.xaml.cs:

public YourView(CustomerVM viewModel)
{
    InitializeComponent();

    this.DataContext = viewModel;
}

The above will work if you are resolving your views through Unity. If not, you can also use the ServiceLocator to resolve the view model:

using Microsoft.Practices.ServiceLocation;

public YourView()
{
    InitializeComponent();

    this.DataContext = ServiceLocator.Current.GetInstance<CustomerVM>();
}

You might also need to add the following somewhere in your registration code to setup the ServiceLocator if you're not using Prism:

ServiceLocator.SetLocatorProvider(new ServiceLocatorProvider(() => new UnityServiceLocator(_unityContainer)));
Mike Payne
  • 614
  • 4
  • 4
  • As soon as I navigate to the view with the view model as parameter get Object reference not set to an instance of an object. ????? Even though I have unitycontainer registering instance of CustomerVM?? – CheGuevarasBeret Oct 25 '12 at 21:06
  • See my edit above on using the ServiceLocator to resolve the CustomerVM. If that doesn't work, can you post your Unity registration code? – Mike Payne Oct 26 '12 at 13:26
  • Hi mike, dev machine is not here but in my app.xaml..cs i have overridden startup and codes something like: UnityContainer container = new UnityContainer container(); container.registertype(); container.registertype(); does this look right? Cheers – CheGuevarasBeret Oct 27 '12 at 08:18