microsoft / Appsample-Photosharing

Sample code for a UWP photo sharing app.
Other
286 stars 116 forks source link

Where view models are registered with the bootstrapper? #24

Closed joshmachol closed 8 years ago

joshmachol commented 8 years ago

I apologize in advance if the answer is obvious, but where do the majority of the view models get registered with the bootstrapper?

In CategoriesView we have

    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        var loadData = e.NavigationMode != NavigationMode.Back;
        _viewModel = ServiceLocator.Current.GetInstance<CategoriesViewModel>(loadData);
        DataContext = _viewModel;

        if (loadData)
        {
            await _viewModel.LoadState();
        }

        _viewModel.StartHeroImageSlideShow();
    }

This makes sense to me because in ViewModelRegistry we have

    public void Configure()
    {
        // We use the container controlled lifetime manager here, as we want to keep instances (for backward navigation)
        // unless we request a new one explicitly (forward navigation).
        Container.RegisterType<CategoriesViewModel>(new ContainerControlledLifetimeManager());
        Container.RegisterType<StreamViewModel>(new ExternallyControlledLifetimeManager());
        Container.RegisterType<IUploadFinishedHandler, DefaultUploadFinishedHandler>();
    }

However, I can't make sense of how the other view models are registered. For example, in AboutPage we have

    public AboutPage()
    {
        InitializeComponent();

        _viewModel = ServiceLocator.Current.GetInstance<AboutViewModel>();
        DataContext = _viewModel;
    }

Where does AboutViewModel get registered?

joshmachol commented 8 years ago

I see now that classes do not need to be registered manually if their constructor dependencies are registered. Closing this.

andystumpp commented 8 years ago

Hi Josh, this is correct, you do not have to register types explicitly. Here's more details: https://msdn.microsoft.com/en-us/library/ff660864(PandP.20).aspx

You can use the Unity container to generate instances of any object that has a public constructor (in other words, objects that you can create using the new operator), without registering a mapping for that type with the container. When you call the Resolve method and specify the default instance of a type that is not registered, the container simply calls the constructor for that type and returns the result.