using DispenserCommon.Interface;
using Microsoft.Extensions.DependencyInjection;
namespace DispenserCommon.Utils;
///
/// 获取服务实例工具类
///
public class ServiceLocator
{
private static IServiceProvider? _serviceProvider;
///
/// 注册 IServiceProvider
///
///
public static void Initialize(IServiceProvider? serviceProvider, IServiceCollection services)
{
_serviceProvider = serviceProvider;
// 注册服务定位器
foreach (var service in services)
{
var serviceType = service.ServiceType;
if (typeof(Instant).IsAssignableFrom(serviceType)) serviceProvider.GetService(service.ServiceType);
}
}
///
/// 获取服务实例
///
///
///
///
public static T GetService() where T : class
{
return _serviceProvider.GetService(typeof(T)) is not T service
? throw new ArgumentException(
$"{typeof(T)} needs to be registered in ConfigureServices within App.axaml.cs.")
: service;
}
///
/// 根据指定的实现类型获取服务实例
///
///
///
///
///
public static T GetService(Type impl) where T : class
{
var services = GetServices();
return services.FirstOrDefault(x => x.GetType() == impl) ?? throw new ArgumentException(
$"{typeof(T)} needs to be registered in ConfigureServices within App.axaml.cs.");
}
public static object? GetService(Type type)
{
return _serviceProvider.GetService(type);
}
///
/// 根据类型获取服务实例
///
///
///
public static IEnumerable GetServices() where T : class
{
var services = _serviceProvider.GetServices();
return services;
}
}