Dispenser/DispenserCommon/Utils/ServiceLocator.cs

75 lines
2.2 KiB
C#
Raw Permalink Normal View History

2024-08-16 07:20:09 +00:00
using DispenserCommon.Interface;
using Microsoft.Extensions.DependencyInjection;
namespace DispenserCommon.Utils;
/// <summary>
/// 获取服务实例工具类
/// </summary>
public class ServiceLocator
{
private static IServiceProvider? _serviceProvider;
/// <summary>
/// 注册 IServiceProvider
/// </summary>
/// <param name="serviceProvider"></param>
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);
}
}
/// <summary>
/// 获取服务实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static T GetService<T>() 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;
}
/// <summary>
/// 根据指定的实现类型获取服务实例
/// </summary>
/// <param name="impl"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static T GetService<T>(Type impl) where T : class
{
var services = GetServices<T>();
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);
}
/// <summary>
/// 根据类型获取服务实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<T> GetServices<T>() where T : class
{
var services = _serviceProvider.GetServices<T>();
return services;
}
}