Skip to content

Commit

Permalink
Merge pull request #7 from RolandKoenig/6-allow-access-to-the-iservic…
Browse files Browse the repository at this point in the history
…eprovider-from-a-usercontrol-class

Added GetServiceProvider as extension method to StyledElement
  • Loading branch information
RolandKoenig authored Dec 30, 2023
2 parents ae67864 + 3bf5eb9 commit da91453
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 da91453

Please sign in to comment.