Files
NebulaLauncher/Nebula.Launcher/ServiceCollectionExtensions.cs

66 lines
2.4 KiB
C#
Raw Permalink Normal View History

2024-12-21 13:11:30 +03:00
using System;
2024-12-22 16:38:47 +03:00
using System.Collections.Generic;
using System.Reflection;
2024-12-21 13:11:30 +03:00
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using Microsoft.Extensions.DependencyInjection;
using Nebula.Launcher.Views;
namespace Nebula.Launcher;
public static class ServiceCollectionExtensions
{
2024-12-30 22:23:55 +03:00
public static void AddAvaloniaServices(this IServiceCollection services)
2024-12-21 13:11:30 +03:00
{
services.AddSingleton<IDispatcher>(_ => Dispatcher.UIThread);
2025-01-14 22:10:16 +03:00
services.AddSingleton(_ =>
Application.Current?.ApplicationLifetime ??
throw new InvalidOperationException("No application lifetime is set"));
2024-12-21 13:11:30 +03:00
services.AddSingleton(sp =>
sp.GetRequiredService<IApplicationLifetime>() switch
{
2025-01-14 22:10:16 +03:00
IClassicDesktopStyleApplicationLifetime desktop => desktop.MainWindow ??
throw new InvalidOperationException(
"No main window set"),
ISingleViewApplicationLifetime singleViewPlatform =>
TopLevel.GetTopLevel(singleViewPlatform.MainView) ??
throw new InvalidOperationException("Could not find top level element for single view"),
_ => throw new InvalidOperationException($"Could not find {nameof(TopLevel)} element")
2024-12-21 13:11:30 +03:00
}
);
services.AddSingleton(sp => sp.GetRequiredService<TopLevel>().StorageProvider);
}
2024-12-30 22:23:55 +03:00
public static void AddViews(this IServiceCollection services)
2024-12-21 13:11:30 +03:00
{
services.AddTransient<MainWindow>();
2024-12-22 16:38:47 +03:00
2025-01-05 17:05:23 +03:00
foreach (var (viewModel, view, isSingleton) in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
2024-12-22 16:38:47 +03:00
{
2025-01-27 15:55:30 +03:00
if (isSingleton)
{
services.AddSingleton(viewModel);
if (view != null) services.AddSingleton(view);
}
else
{
services.AddTransient(viewModel);
if (view != null) services.AddTransient(view);
}
2024-12-22 16:38:47 +03:00
}
}
2025-01-14 22:10:16 +03:00
private static IEnumerable<(Type, Type?, bool)> GetTypesWithHelpAttribute(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
2024-12-22 16:38:47 +03:00
{
2025-01-05 17:05:23 +03:00
var attr = type.GetCustomAttribute<ViewModelRegisterAttribute>();
2025-01-14 22:10:16 +03:00
if (attr is not null) yield return (type, attr.Type, attr.IsSingleton);
2024-12-22 16:38:47 +03:00
}
}
2025-01-14 22:10:16 +03:00
}