| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ViewModelLocator.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | |
| | | 9 | | namespace MyNet.UI.Locators; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Implements a view model locator that uses an IServiceProvider to resolve view model instances. This allows for depen |
| | | 13 | | /// </summary> |
| | | 14 | | /// <param name="provider">The service provider used to resolve view model instances.</param> |
| | | 15 | | public sealed class ViewModelLocator(IServiceProvider provider) : IViewModelLocator |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Resolves a view model instance based on the specified view model type. The locator uses the provided IServicePro |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="viewModelType">The type of the view model to retrieve.</param> |
| | | 21 | | /// <returns>The view model instance.</returns> |
| | | 22 | | public object Get(Type viewModelType) |
| | | 23 | | { |
| | 6 | 24 | | ArgumentNullException.ThrowIfNull(viewModelType); |
| | | 25 | | |
| | 6 | 26 | | return provider.GetService(viewModelType) ?? throw new InvalidOperationException($"Cannot create instance of {vi |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Resolves a view model instance of the specified generic type. This allows for type-safe retrieval of view models |
| | | 31 | | /// </summary> |
| | | 32 | | /// <typeparam name="T">The type of the view model to retrieve.</typeparam> |
| | | 33 | | /// <returns>The view model instance.</returns> |
| | | 34 | | public T Get<T>() |
| | 6 | 35 | | where T : class => (T)Get(typeof(T)); |
| | | 36 | | } |
| | | 37 | | |