0
votes

I am designing a WPF application with several ViewModels, and I am using Caliburn Micro and MEF. Unfortunately, I am absolutely new to MEF and IoC, and can't solve a problem.

The application is supposed to have a MainView, where several options are enlisted, like: Create a new record, Edit older records, View reports, etc. So, for each of those units, I have different classes for ViewModels like CreateRecordViewModel, EditRecordsViewModel, ViewReportsViewModel, and Usercontrols for Views like CreateRecordView, EditRecordsView, ViewReportsView etc.

Now, the MainViewModel is a Conductor, and I am using code like this:

public class ShellViewModel : Conductor<object> 
{         
     public void ShowCreateRecord()
     {
          ActivateItem(new CreateRecordViewModel(...Dependencies...));
     }

     public void ShowEditRecords() 
     {
          ActivateItem(new EditRecordsViewModel(...Dependencies...));
     }

     ...
}

Since the MEF container resides in Bootstrapper, I am a bit lost about how to use Constructor Injection in this MainViewModel. And my second concern is about GC. How can I test if the created ViewModels are properly disposed of?

I know these questions might seem a bit asinine, but I would really appreciate a solution. Should I decorate my Property setters with [Import] instead of going for Constructor Injection?

1

1 Answers

1
votes

I am not familiar with MEF myself, but most of the DIs work in a similar idea. You have to inject the container's (MEF container) into the view models, and resolve the appropriate viewmodels using the container.

You're not supposed to instantiate viewmodels by yourself, instead, in the main vm, inject the container resolving service, via constructor or property injection (again - not so familiar with MEF), then call ActivateItem(_DependencyService.Resolve<CreateRecordViewModel>());.

And BTW, the Main VM itself should also be instantiated by the container, so you obviously don't need to manually inject the container to the main vm.

IoC is just about trusting the container to resolve anything for you, otherwise, its the container registered types that are misregistered:

public class ShellViewModel : Conductor<object> 
{
  private readonly IMefDependencyContainer _container;      
  public ShellViewModel(IMefDependencyContainer container) {
    _container = container;   
  }     

  public void ShowCreateRecord()
  {
    ActivateItem(_container.Resolve<CreateRecordViewModel>());
  }
}

Replace IMefDependencyContainer and Resolve with its names in MEF.