Skip to content

Commit e4116ca

Browse files
committed
Added Ioc.GetRequiredService<T> method
1 parent eb42db0 commit e4116ca

File tree

1 file changed

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

1 file changed

+38
-0
lines changed

Microsoft.Toolkit.Mvvm/DependencyInjection/Ioc.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ public sealed class Ioc : IServiceProvider
8383
/// </summary>
8484
/// <typeparam name="T">The type of service to resolve.</typeparam>
8585
/// <returns>An instance of the specified service, or <see langword="null"/>.</returns>
86+
/// <exception cref="InvalidOperationException">Throw if the current <see cref="Ioc"/> instance has not been initialized.</exception>
8687
public T? GetService<T>()
8788
where T : class
8889
{
@@ -96,6 +97,35 @@ public sealed class Ioc : IServiceProvider
9697
return (T?)provider!.GetService(typeof(T));
9798
}
9899

100+
/// <summary>
101+
/// Resolves an instance of a specified service type.
102+
/// </summary>
103+
/// <typeparam name="T">The type of service to resolve.</typeparam>
104+
/// <returns>An instance of the specified service, or <see langword="null"/>.</returns>
105+
/// <exception cref="InvalidOperationException">
106+
/// Throw if the current <see cref="Ioc"/> instance has not been initialized, or if the
107+
/// requested service type was not registered in the service provider currently in use.
108+
/// </exception>
109+
public T GetRequiredService<T>()
110+
where T : class
111+
{
112+
IServiceProvider? provider = this.serviceProvider;
113+
114+
if (provider is null)
115+
{
116+
ThrowInvalidOperationExceptionForMissingInitialization();
117+
}
118+
119+
T? service = (T?)provider!.GetService(typeof(T));
120+
121+
if (service is null)
122+
{
123+
ThrowInvalidOperationExceptionForUnregisteredType();
124+
}
125+
126+
return service!;
127+
}
128+
99129
/// <summary>
100130
/// Initializes the shared <see cref="IServiceProvider"/> instance.
101131
/// </summary>
@@ -118,6 +148,14 @@ private static void ThrowInvalidOperationExceptionForMissingInitialization()
118148
throw new InvalidOperationException("The service provider has not been configured yet");
119149
}
120150

151+
/// <summary>
152+
/// Throws an <see cref="InvalidOperationException"/> when the <see cref="IServiceProvider"/> property is missing a type registration.
153+
/// </summary>
154+
private static void ThrowInvalidOperationExceptionForUnregisteredType()
155+
{
156+
throw new InvalidOperationException("The requested service type was not registered");
157+
}
158+
121159
/// <summary>
122160
/// Throws an <see cref="InvalidOperationException"/> when a configuration is attempted more than once.
123161
/// </summary>

0 commit comments

Comments
 (0)