Skip to content

Commit

Permalink
Added GetServiceProvider as extension method to StyledElement
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandKoenig committed Dec 30, 2023
1 parent ae67864 commit 3bf5eb9
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
}

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

namespace RolandK.AvaloniaExtensions.DependencyInjection;

public static class ControlExtensions
{
/// <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)
{
if(control.TryFindResource(DependencyInjectionConstants.SERVICE_PROVIDER_RESOURCE_KEY, out var resource) &&
resource is IServiceProvider serviceProvider)
{
return serviceProvider;
}
return null;
}

/// <summary>
/// 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)
{
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;
}
}

0 comments on commit 3bf5eb9

Please sign in to comment.