From 3bf5eb91d319e2ac240da10b3c8afc81271a7e5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20K=C3=B6nig?= Date: Sat, 30 Dec 2023 20:22:53 +0100 Subject: [PATCH] Added GetServiceProvider as extension method to StyledElement --- .../DependencyInjectionTests.cs | 23 ++++++++++++ .../ControlExtensions.cs | 36 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/RolandK.AvaloniaExtensions.DependencyInjection/ControlExtensions.cs diff --git a/src/RolandK.AvaloniaExtensions.DependencyInjection.Tests/DependencyInjectionTests.cs b/src/RolandK.AvaloniaExtensions.DependencyInjection.Tests/DependencyInjectionTests.cs index a9de860..0bfe18b 100644 --- a/src/RolandK.AvaloniaExtensions.DependencyInjection.Tests/DependencyInjectionTests.cs +++ b/src/RolandK.AvaloniaExtensions.DependencyInjection.Tests/DependencyInjectionTests.cs @@ -118,6 +118,29 @@ public Task Assign_ViewModel_by_CreateUsingDependencyInjectionExtension_after_at testWindow.Close(); }); } + + [Fact] + public Task Create_Control_and_get_ServiceProvider_from_it() + { + return UnitTestApplication.RunInApplicationContextAsync(() => + { + // Arrange + var myUserControl = new UserControl(); + + // Act + var testWindow = new TestRootWindow(myUserControl); + testWindow.Show(); + + var serviceProvider = myUserControl.GetServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider); + Assert.NotNull(serviceProvider.GetService(typeof(IDummyService))); + + // Cleanup + testWindow.Close(); + }); + } //************************************************************************* //************************************************************************* diff --git a/src/RolandK.AvaloniaExtensions.DependencyInjection/ControlExtensions.cs b/src/RolandK.AvaloniaExtensions.DependencyInjection/ControlExtensions.cs new file mode 100644 index 0000000..b1976c0 --- /dev/null +++ b/src/RolandK.AvaloniaExtensions.DependencyInjection/ControlExtensions.cs @@ -0,0 +1,36 @@ +using Avalonia; +using Avalonia.Controls; + +namespace RolandK.AvaloniaExtensions.DependencyInjection; + +public static class ControlExtensions +{ + /// + /// Gets the for this application. + /// Returns null, if the could not be found. + /// + public static IServiceProvider? TryGetServiceProvider(this StyledElement control) + { + if(control.TryFindResource(DependencyInjectionConstants.SERVICE_PROVIDER_RESOURCE_KEY, out var resource) && + resource is IServiceProvider serviceProvider) + { + return serviceProvider; + } + return null; + } + + /// + /// Gets the for this application. + /// + /// could not be found + public static IServiceProvider GetServiceProvider(this StyledElement control) + { + var serviceProvider = TryGetServiceProvider(control); + if (serviceProvider == null) + { + throw new InvalidOperationException( + $"{nameof(IServiceProvider)} not found! Call to {nameof(AppBuilderExtensions.UseDependencyInjection)} in Program.cs may be missing..."); + } + return serviceProvider; + } +}