Skip to content

Commit fb17f61

Browse files
committed
Added generic Ioc.GetService<T> method
1 parent 66825f9 commit fb17f61

File tree

1 file changed

+18
-0
lines changed
  • Microsoft.Toolkit.Mvvm/DependencyInjection

1 file changed

+18
-0
lines changed

Microsoft.Toolkit.Mvvm/DependencyInjection/Ioc.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,24 @@ public sealed class Ioc : IServiceProvider
7878
return provider!.GetService(serviceType);
7979
}
8080

81+
/// <summary>
82+
/// Tries to resolve an instance of a specified service type.
83+
/// </summary>
84+
/// <typeparam name="T">The type of service to resolve.</typeparam>
85+
/// <returns>An instance of the specified service, or <see langword="null"/>.</returns>
86+
public T? GetService<T>()
87+
where T : class
88+
{
89+
IServiceProvider? provider = this.serviceProvider;
90+
91+
if (provider is null)
92+
{
93+
ThrowInvalidOperationExceptionForMissingInitialization();
94+
}
95+
96+
return (T?)provider!.GetService(typeof(T));
97+
}
98+
8199
/// <summary>
82100
/// Initializes the shared <see cref="IServiceProvider"/> instance.
83101
/// </summary>

0 commit comments

Comments
 (0)