Skip to content

Commit

Permalink
Updated GetServiceProvider and TryGetServiceProvider to be extension …
Browse files Browse the repository at this point in the history
…methods of IResourceHost
  • Loading branch information
RolandKoenig committed Jan 3, 2024
1 parent d0f5cb5 commit fcc5cbe
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,20 @@ public Task Create_Control_and_get_ServiceProvider_from_it()
});
}

[Fact]
public Task Get_ServiceProvider_from_Application()
{
return UnitTestApplication.RunInApplicationContextAsync(() =>
{
// Act
var serviceProvider = Application.Current?.GetServiceProvider();

// Assert
Assert.NotNull(serviceProvider);
Assert.NotNull(serviceProvider.GetService(typeof(IDummyService)));
});
}

//*************************************************************************
//*************************************************************************
//*************************************************************************
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using Avalonia;
using Avalonia.Controls;

namespace RolandK.AvaloniaExtensions.DependencyInjection;

public static class ControlExtensions
public static class IResourceHostExtensions
{
/// <summary>
/// Gets the <see cref="IServiceProvider"/> for this application.
/// Returns null, if the <see cref="IServiceProvider"/> could not be found.
/// </summary>
public static IServiceProvider? TryGetServiceProvider(this StyledElement control)
public static IServiceProvider? TryGetServiceProvider(this IResourceHost control)
{
if(control.TryFindResource(DependencyInjectionConstants.SERVICE_PROVIDER_RESOURCE_KEY, out var resource) &&
resource is IServiceProvider serviceProvider)
Expand All @@ -23,7 +22,7 @@ public static class ControlExtensions
/// Gets the <see cref="IServiceProvider"/> for this application.
/// </summary>
/// <exception cref="InvalidOperationException"><see cref="IServiceProvider"/> could not be found</exception>
public static IServiceProvider GetServiceProvider(this StyledElement control)
public static IServiceProvider GetServiceProvider(this IResourceHost control)
{
var serviceProvider = TryGetServiceProvider(control);
if (serviceProvider == null)
Expand All @@ -33,4 +32,4 @@ public static IServiceProvider GetServiceProvider(this StyledElement control)
}
return serviceProvider;
}
}
}

0 comments on commit fcc5cbe

Please sign in to comment.