From e84b5f824475a05ab54a9e49b8246b42bb1aa4e7 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Wed, 22 Dec 2021 15:07:55 +0100 Subject: [PATCH] Added AvaloniaLocation.GetRequiredService. Using the pattern from elsewhere e.g. https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.getrequiredservice?view=dotnet-plat-ext-6.0 --- src/Avalonia.Base/AvaloniaLocator.cs | 10 ++++++++++ src/Avalonia.Controls/SystemDialog.cs | 9 +++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Avalonia.Base/AvaloniaLocator.cs b/src/Avalonia.Base/AvaloniaLocator.cs index 0510852ea7..8ec245507b 100644 --- a/src/Avalonia.Base/AvaloniaLocator.cs +++ b/src/Avalonia.Base/AvaloniaLocator.cs @@ -125,6 +125,16 @@ namespace Avalonia { return (T?) resolver.GetService(typeof (T)); } + + public static object GetRequiredService(this IAvaloniaDependencyResolver resolver, Type t) + { + return resolver.GetService(t) ?? throw new InvalidOperationException($"Unable to locate '{t}'."); + } + + public static T GetRequiredService(this IAvaloniaDependencyResolver resolver) + { + return (T?)resolver.GetService(typeof(T)) ?? throw new InvalidOperationException($"Unable to locate '{typeof(T)}'."); + } } } diff --git a/src/Avalonia.Controls/SystemDialog.cs b/src/Avalonia.Controls/SystemDialog.cs index 3fac10b2d1..3487f427d7 100644 --- a/src/Avalonia.Controls/SystemDialog.cs +++ b/src/Avalonia.Controls/SystemDialog.cs @@ -66,8 +66,7 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - var service = AvaloniaLocator.Current.GetService() ?? - throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + var service = AvaloniaLocator.Current.GetRequiredService(); return (await service.ShowFileDialogAsync(this, parent) ?? Array.Empty()).FirstOrDefault(); } @@ -95,8 +94,7 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - var service = AvaloniaLocator.Current.GetService() ?? - throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + var service = AvaloniaLocator.Current.GetRequiredService(); return service.ShowFileDialogAsync(this, parent); } } @@ -125,8 +123,7 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - var service = AvaloniaLocator.Current.GetService() ?? - throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + var service = AvaloniaLocator.Current.GetRequiredService(); return service.ShowFolderDialogAsync(this, parent); } }