using Microsoft.Extensions.DependencyInjection; using System.Linq; using System.Runtime.InteropServices; using Xamarin.Essentials; namespace System { /// /// 依赖注入服务组(DependencyInjection) /// public static class DI { static IServiceProvider? value; internal static bool IsInit => value != null; internal static IServiceProvider Value => value ?? throw new NullReferenceException("init must be called."); /// /// 初始化依赖注入服务组(通过配置服务项的方式) /// /// public static void Init(Action configureServices) { var services = new ServiceCollection(); configureServices(services); Init(services.BuildServiceProvider()); } /// /// 初始化依赖注入服务组(直接赋值) /// /// public static void Init(IServiceProvider serviceProvider) { value = serviceProvider; } /// public static Platform Platform { get; } /// public static DeviceIdiom DeviceIdiom { get; private set; } /// /// 当前是否使用Mono运行时 /// public static bool IsRunningOnMono { get; } const string DesktopWindowTypeNames = "Avalonia.Controls.Window, Avalonia.Controls" + "\n" + "System.Windows.Forms.Form, System.Windows.Forms" + "\n" + "System.Windows.Window, PresentationFramework"; static DI() { IsRunningOnMono = Type.GetType("Mono.Runtime") != null; static Platform RuntimeInformationOSPlatform() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Platform.Windows; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return Platform.Apple; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return Platform.Linux; return Platform.Unknown; } static DeviceIdiom GetDeviceIdiom() { if (DesktopWindowTypeNames.Split('\n') .Any(x => Type.GetType(x) != null)) return DeviceIdiom.Desktop; return DeviceIdiom.Unknown; } Platform = DeviceInfo.Platform.Convert(); if (Platform == Platform.Unknown) Platform = RuntimeInformationOSPlatform(); DeviceIdiom = DeviceInfo.Idiom.Convert(); if (DeviceIdiom == DeviceIdiom.Unknown) DeviceIdiom = GetDeviceIdiom(); } /// /// 获取依赖注入服务 /// /// /// public static T Get() where T : notnull => Value.GetRequiredService(); /// public static T? Get_Nullable() where T : notnull => Value.GetService(); /// public static object Get(Type serviceType) => Value.GetRequiredService(serviceType); /// public static object? Get_Nullable(Type serviceType) => Value.GetService(serviceType); } }