// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Testing.Platform.Extensions;
using Microsoft.Testing.Platform.Resources;
using Microsoft.Testing.Platform.Services;
namespace Microsoft.Testing.Platform.Helpers;
///
/// Shared helpers implementing the common "instantiate → validate unique → check enabled →
/// initialize → register" loop used to build platform extensions across the various
/// *Manager classes.
///
internal static class ExtensionBuilderHelper
{
///
/// Builds and registers extensions produced by simple factories into .
/// For each factory the extension is instantiated, validated for uniqueness, and — when enabled —
/// initialized and added to the result (optionally registered in the service provider).
///
/// The extension type produced by the factories.
public static async Task BuildAndRegisterExtensionsAsync(
IEnumerable> factories,
ServiceProvider serviceProvider,
List result,
bool registerInServiceProvider = false)
where T : class, IExtension
{
foreach (Func factory in factories)
{
T service = factory(serviceProvider);
// Check if we have already extensions of the same type with same id registered
result.ValidateUniqueExtension(service);
// We initialize only if enabled
if (await service.IsEnabledAsync().ConfigureAwait(false))
{
await service.TryInitializeAsync().ConfigureAwait(false);
// Register the extension for usage
result.Add(service);
if (registerInServiceProvider)
{
serviceProvider.TryAddService(service);
}
}
}
}
///
/// Builds and registers extensions produced by simple factories into ,
/// preserving the registration order captured in .
///
/// The extension type produced by the factories.
public static async Task BuildAndRegisterExtensionsAsync(
IEnumerable> factories,
ServiceProvider serviceProvider,
List<(IExtension Extension, int RegistrationOrder)> result,
List