ck84vi
ck84vi

Reputation: 1586

How/Where to instantiate model objects in MVVM using PRISM and Unity

I try to implement my first application using PRISM and UNITY. So i try to split my application in several modules.

In my modules i have the related view as well as the view model.

Currently i instantiate my viewmodel and set the datacontext of my view in the views code behind:

public partial class View : UserControl
{
    public View(IViewModel vm)
    {
        InitializeComponent();
        this.DataContext = vm;
    }
}

My model is instantiated using the unity-container in my view-models ctor.

public ViewModel(IEventAggregator eventAggregator, IUnityContainer container)
{
    _eventAggregator = eventAggregator;

    _model = container.Resolve<Model>();
    this._model.PropertyChanged += new PropertyChangedEventHandler(OnModelPropertyChanged);
}

Before i used the unity container i injected the models by dependency injection via the ViewModels constructor.

But this seems not to work. I tried it in the following way:

public ViewModel(IEventAggregator eventAggregator, Model model)
{
    _eventAggregator = eventAggregator;
    _model = model
    this._model.PropertyChanged += new PropertyChangedEventHandler(OnModelPropertyChanged);
}

This implementation gives me an exception and i also couldn't find out how to setup the container so that the model injection works in the way i tried.

What i would like to do is to instantiate my models in the module class. And from there i would like to inject it to my viewmodels.

So my questions are:

  1. Is the way i do it currently correct?
  2. Is there a way to instantiate the models in the module class and inject them to the viewmodels, if so how and are there any examples on the web?

Upvotes: 1

Views: 1215

Answers (1)

al_amanat
al_amanat

Reputation: 615

Look at UI Composition QuickStart of Prism 5 (http://msdn.microsoft.com/en-us/library/gg430879(v=pandp.40).aspx). It does exactly what you want.
1) Register module in your Bootstrapper:

moduleCatalog.AddModule(typeof(EmployeeModule.ModuleInit));

2) Register your model type in your module inplementation (or in bootstrapper if your model is shared)

this.container.RegisterType<IEmployeeDataService, EmployeeDataService>();

3) Inject model into your view model via constructor

public EmployeeListViewModel(IEmployeeDataService dataService, IEventAggregator eventAggregator) { }

Upvotes: 2

Related Questions