| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ViewLocator.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 the IViewLocator interface to provide a mechanism for locating and instantiating views based on their typ |
| | | 13 | | /// </summary> |
| | | 14 | | /// <param name="provider">The service provider used to resolve view instances.</param> |
| | | 15 | | public sealed class ViewLocator(IServiceProvider provider) : IViewLocator |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Retrieves a view instance based on the specified view type. The locator first attempts to resolve the view type |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="viewType">The type of the view to retrieve.</param> |
| | | 21 | | /// <returns>The view instance.</returns> |
| | | 22 | | public object Get(Type viewType) |
| | | 23 | | { |
| | 27 | 24 | | ArgumentNullException.ThrowIfNull(viewType); |
| | | 25 | | |
| | 24 | 26 | | if (provider.GetService(viewType) is { } instance) |
| | 3 | 27 | | return instance; |
| | | 28 | | |
| | | 29 | | try |
| | | 30 | | { |
| | 21 | 31 | | return Activator.CreateInstance(viewType) |
| | 21 | 32 | | ?? throw ViewResolutionException.CannotInstantiateView(viewType); |
| | | 33 | | } |
| | 0 | 34 | | catch (ViewResolutionException) |
| | | 35 | | { |
| | 0 | 36 | | throw; |
| | | 37 | | } |
| | 0 | 38 | | catch (Exception ex) |
| | | 39 | | { |
| | 0 | 40 | | throw ViewResolutionException.CannotInstantiateView(viewType, ex); |
| | | 41 | | } |
| | 21 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Retrieves a view instance of the specified generic type. This method provides a type-safe way to retrieve views |
| | | 46 | | /// </summary> |
| | | 47 | | /// <typeparam name="T">The type of the view to retrieve.</typeparam> |
| | | 48 | | /// <returns>The view instance of type T.</returns> |
| | | 49 | | public T Get<T>() |
| | 9 | 50 | | where T : class => (T)Get(typeof(T)); |
| | | 51 | | } |
| | | 52 | | |