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 ;
2024-12-22 16:38:47 +03:00
using Nebula.Launcher.ViewHelper ;
2024-12-21 13:11:30 +03:00
using Nebula.Launcher.ViewModels ;
using Nebula.Launcher.Views ;
using Nebula.Launcher.Views.Pages ;
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 ) ;
services . AddSingleton ( _ = > Application . Current ? . ApplicationLifetime ? ? throw new InvalidOperationException ( "No application lifetime is set" ) ) ;
services . AddSingleton ( sp = >
sp . GetRequiredService < IApplicationLifetime > ( ) switch
{
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" ) ,
}
) ;
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-05 17:05:23 +03:00
if ( isSingleton ) services . AddSingleton ( viewModel ) ;
else services . AddTransient ( viewModel ) ;
if ( view ! = null ) services . AddTransient ( view ) ;
2024-12-22 16:38:47 +03:00
}
}
2025-01-05 17:05:23 +03:00
private static IEnumerable < ( Type , Type ? , bool ) > GetTypesWithHelpAttribute ( Assembly assembly ) {
2024-12-22 16:38:47 +03:00
foreach ( Type type in assembly . GetTypes ( ) )
{
2025-01-05 17:05:23 +03:00
var attr = type . GetCustomAttribute < ViewModelRegisterAttribute > ( ) ;
2024-12-22 16:38:47 +03:00
if ( attr is not null ) {
2025-01-05 17:05:23 +03:00
yield return ( type , attr . Type , attr . IsSingleton ) ;
2024-12-22 16:38:47 +03:00
}
}
}
}