-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added GetServiceProvider as extension method to StyledElement
- Loading branch information
1 parent
ae67864
commit 3bf5eb9
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
src/RolandK.AvaloniaExtensions.DependencyInjection/ControlExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |