41 lines
1.8 KiB
C#
41 lines
1.8 KiB
C#
namespace DigitalData.Core.Abstractions;
|
|
|
|
/// <summary>
|
|
/// A deferred implementation of <see cref="IServiceProvider"/> that allows the <see cref="IServiceProvider"/> instance
|
|
/// to be provided at a later time via a factory callback.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// This is particularly useful when service registration requires an <see cref="IServiceProvider"/> instance,
|
|
/// but the service provider is not yet available at registration time.
|
|
/// By using <see cref="DeferredServiceProvider"/>, a service can safely resolve dependencies once
|
|
/// the application's service provider has been built, ensuring a single consistent scope.
|
|
/// </remarks>
|
|
public class DeferredServiceProvider : IServiceProvider
|
|
{
|
|
private Lazy<IServiceProvider>? _serviceProvider;
|
|
|
|
/// <summary>
|
|
/// Sets the factory that will be used to lazily initialize the <see cref="IServiceProvider"/> instance.
|
|
/// </summary>
|
|
public Func<IServiceProvider> Factory
|
|
{
|
|
set => _serviceProvider = new(value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieves the requested service object from the deferred <see cref="IServiceProvider"/>.
|
|
/// </summary>
|
|
/// <param name="serviceType">The type of service object to retrieve.</param>
|
|
/// <returns>The requested service object, or <c>null</c> if the service is not available.</returns>
|
|
/// <exception cref="InvalidOperationException">
|
|
/// Thrown if the service provider factory has not been set before calling <see cref="GetService"/>.
|
|
/// </exception>
|
|
public object? GetService(Type serviceType)
|
|
{
|
|
if (_serviceProvider is null)
|
|
throw new InvalidOperationException("The service provider has not been initialized. Make sure 'Factory' is set before calling 'GetService'.");
|
|
|
|
return _serviceProvider.Value.GetService(serviceType);
|
|
}
|
|
}
|