Files
SteamTools/System.Common.CoreLib/DI.cs
T
2021-02-20 16:45:44 +08:00

99 lines
3.5 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Runtime.InteropServices;
using Xamarin.Essentials;
namespace System
{
/// <summary>
/// 依赖注入服务组(DependencyInjection)
/// </summary>
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.");
/// <summary>
/// 初始化依赖注入服务组(通过配置服务项的方式)
/// </summary>
/// <param name="configureServices"></param>
public static void Init(Action<IServiceCollection> configureServices)
{
var services = new ServiceCollection();
configureServices(services);
Init(services.BuildServiceProvider());
}
/// <summary>
/// 初始化依赖注入服务组(直接赋值)
/// </summary>
/// <param name="serviceProvider"></param>
public static void Init(IServiceProvider serviceProvider)
{
value = serviceProvider;
}
/// <inheritdoc cref="System.Platform"/>
public static Platform Platform { get; }
/// <inheritdoc cref="System.DeviceIdiom"/>
public static DeviceIdiom DeviceIdiom { get; private set; }
/// <summary>
/// 当前是否使用Mono运行时
/// </summary>
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();
}
/// <summary>
/// 获取依赖注入服务
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Get<T>() where T : notnull => Value.GetRequiredService<T>();
/// <inheritdoc cref="Get{T}"/>
public static T? Get_Nullable<T>() where T : notnull => Value.GetService<T>();
/// <inheritdoc cref="Get{T}"/>
public static object Get(Type serviceType) => Value.GetRequiredService(serviceType);
/// <inheritdoc cref="Get_Nullable{T}"/>
public static object? Get_Nullable(Type serviceType) => Value.GetService(serviceType);
}
}