Search code examples
c#wpfmvvmunity-containerprism-6

How is this viewModel being created?


I have a simple application here but I am unsure of how my ViewModel is being created. I am assuming it's from the unity container but I am unsure and curious. The module initializes and registers the view with the region. The view's code behind has the ViewModel initialized in it's constructor and the ViewModel calls some services that were previously registered.

My question is how is the ViewModel created in the View's code behind when I've never registered the ViewModel type with the unity container? Is there some magic happening in the RegisterViewWithRegion method?

AlarmsModule.cs: This simply registers the view with the region

[Module(ModuleName = "AlarmsModule")]
public class AlarmsModule : IModule
{
    [Dependency]
    public IRegionManager regionManager { get; set; }

    public void Initialize()
    {           

        regionManager.RegisterViewWithRegion("AlarmsRegion", typeof(AlarmPanel.View));                 

    }

}

View.xaml.cs:

 public partial class View : UserControl
{
    public View(ViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
}

ViewModel.cs

public class ViewModel: DependencyObject
{
    IEventAggregator _eventAggregator;

    public ObservableCollection<IAlarmContainer> AlarmList { get; set; }

    IAlarmService _alarmService;
    public ViewModel(IAlarmService alarmService)
    {
        //Adding an alarm from the alarm service, which is injected into this viewModel
        AlarmList = alarmService.AlarmList;
    }
}

Solution

  • The view model is created by the unity container in the DoGetInstance method of the UnityServiceLocatorAdapter class in the Prism.Unity assembly which is in turn called by the RegisterViewWithRegion method through some other methods of the RegionViewRegistry class.

    Unity is able to resolve the view model type automatically provided that it has a default parameterless constructor.

    You could verify this yourself using the following code:

    var view = unityContainer.Resolve(typeof(View), null); //will automatically resolve the view model type and inject the view with an instance of it