//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SqlTools.Hosting.Utility;
namespace Microsoft.SqlTools.Hosting.Extensibility
{
public interface IMultiServiceProvider
{
///
/// Gets a service of a specific type. It is expected that only 1 instance of this type will be
/// available
///
/// Type of service to be found
/// Instance of T or null if not found
/// The input sequence contains more than one element.-or-The input sequence is empty.
T GetService();
///
/// Gets a service of a specific type. The first service matching the specified filter will be returned
/// available
///
/// Type of service to be found
/// Filter to use in
/// Instance of T or null if not found
/// The input sequence contains more than one element.-or-The input sequence is empty.
T GetService(Predicate filter);
///
/// Gets multiple services of a given type
///
///
/// An enumerable of matching services
IEnumerable GetServices();
///
/// Gets multiple services of a given type, where they match a filter
///
///
///
///
IEnumerable GetServices(Predicate filter);
}
public abstract class ServiceProviderBase : IMultiServiceProvider
{
public T GetService()
{
return GetServices().SingleOrDefault();
}
public T GetService(Predicate filter)
{
Validate.IsNotNull(nameof(filter), filter);
return GetServices().SingleOrDefault(t => filter(t));
}
public IEnumerable GetServices(Predicate filter)
{
Validate.IsNotNull(nameof(filter), filter);
return GetServices().Where(t => filter(t));
}
public virtual IEnumerable GetServices()
{
var services = GetServicesImpl();
if (services == null)
{
return Enumerable.Empty();
}
return services.Select(t =>
{
InitComposableService(t);
return t;
});
}
private void InitComposableService(T t)
{
IComposableService c = t as IComposableService;
c?.SetServiceProvider(this);
}
///
/// Gets all services using the build in implementation
///
///
///
protected abstract IEnumerable GetServicesImpl();
}
}