From c6e9bf4e82c6f9749422b96fa64d6c7f1ebc1df8 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 15:09:35 +0100 Subject: [PATCH] refactor: build services with dependency injection App registers the services, controllers, the main window and the pages in a container, and the navigation view asks it for each page. Pages get their controllers through the constructor instead of reading statics from App. SettingsStore takes over the current settings from App. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/App.xaml | 3 +- src/Radiosender/App.xaml.cs | 71 +++++++++++++------ .../Controllers/ScheduleController.cs | 2 +- src/Radiosender/Radiosender.csproj | 1 + src/Radiosender/Services/SettingsStore.cs | 31 ++++++++ src/Radiosender/Views/MainWindow.xaml.cs | 14 +++- .../Views/Pages/LibraryPage.xaml.cs | 8 ++- .../Views/Pages/SchedulePage.xaml.cs | 5 +- .../Views/Pages/SettingsPage.xaml.cs | 12 +++- 9 files changed, 112 insertions(+), 35 deletions(-) create mode 100644 src/Radiosender/Services/SettingsStore.cs diff --git a/src/Radiosender/App.xaml b/src/Radiosender/App.xaml index 9462f47..e8c3723 100644 --- a/src/Radiosender/App.xaml +++ b/src/Radiosender/App.xaml @@ -1,8 +1,7 @@  + xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"> diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs index 212796f..f0120d7 100644 --- a/src/Radiosender/App.xaml.cs +++ b/src/Radiosender/App.xaml.cs @@ -1,45 +1,72 @@ using System.Windows; +using Microsoft.Extensions.DependencyInjection; using Radiosender.Controllers; using Radiosender.Services; +using Radiosender.Views; +using Radiosender.Views.Pages; namespace Radiosender; +/// Composition root: wires every service, controller and page once, at startup. public partial class App : Application { - public static SongRepository Songs { get; private set; } = null!; + private ServiceProvider? _services; - /// App-wide, so a running broadcast keeps going while the user switches pages. - public static ScheduleController Schedule { get; private set; } = null!; - - public static AppSettings Settings { get; private set; } = new(); - - private static readonly ScheduleGenerator Generator = new(); - - /// Stores the settings and applies them: alerts at once, minutes per hour from the next plan on. - /// The settings file cannot be written. - /// The settings file cannot be written. - public static void SaveSettings(AppSettings settings) + private static ServiceProvider BuildServices() { - settings.Save(AppSettings.DefaultPath); - Settings = settings; - Generator.Options = settings.ToScheduleOptions(); + var services = new ServiceCollection(); + + // One instance each for the whole app. The schedule controller in particular must be shared, + // so a running broadcast keeps going while the user switches pages. + services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath)); + services.AddSingleton(_ => new ScheduleGenerator()); + services.AddSingleton(provider => new SettingsStore(provider.GetRequiredService(), AppSettings.DefaultPath)); + services.AddSingleton(_ => new PlaybackEngine()); + services.AddSingleton(provider => new ScheduleController( + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService(), + () => DateTime.Now)); + // One HttpClient for all providers and downloads. + services.AddSingleton(_ => + { + var http = new System.Net.Http.HttpClient { Timeout = TimeSpan.FromSeconds(20) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("Radiosender/1.0"); + return http; + }); + // Music providers: add a line here for each new IMusicProvider; the import page lists them all. + services.AddSingleton(); + services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService(), TrackDownloader.DefaultMusicFolder)); + services.AddSingleton(); + services.AddSingleton(provider => new SongImportService(provider.GetRequiredService(), SongImportService.DefaultMusicDirectory)); + services.AddSingleton(); + services.AddSingleton(); + + // Pages are created anew on every navigation, as before; they hold only view state. + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services.BuildServiceProvider(); } protected override void OnStartup(StartupEventArgs e) { - Settings = AppSettings.Load(AppSettings.DefaultPath); - Generator.Options = Settings.ToScheduleOptions(); - // Creates the database file and table on first start. - Songs = new SongRepository(SongRepository.DefaultDatabasePath); - Schedule = new ScheduleController(Songs, Generator, new PlaybackEngine(), () => DateTime.Now); + base.OnStartup(e); + _services = BuildServices(); + // Loads the settings and gives the generator its minutes per hour before the first plan. + _services.GetRequiredService(); // Follow the Windows setting: light, dark or a high-contrast theme. Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme(); - base.OnStartup(e); + _services.GetRequiredService().Show(); } protected override void OnExit(ExitEventArgs e) { - Schedule.Stop(); + _services?.GetRequiredService().Stop(); + _services?.Dispose(); base.OnExit(e); } } diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs index ed5a1b8..ef8cd31 100644 --- a/src/Radiosender/Controllers/ScheduleController.cs +++ b/src/Radiosender/Controllers/ScheduleController.cs @@ -5,7 +5,7 @@ namespace Radiosender.Controllers; /// /// Creates the broadcast plan and drives its playback. One instance lives for the whole app -/// (), so the plan survives page navigation. +/// (registered as a singleton in ), so the plan survives page navigation. /// /// Events come from the playback engine's thread pool; views marshal with Dispatcher.BeginInvoke. public class ScheduleController diff --git a/src/Radiosender/Radiosender.csproj b/src/Radiosender/Radiosender.csproj index 91374ec..8d35088 100644 --- a/src/Radiosender/Radiosender.csproj +++ b/src/Radiosender/Radiosender.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Radiosender/Services/SettingsStore.cs b/src/Radiosender/Services/SettingsStore.cs new file mode 100644 index 0000000..5414b95 --- /dev/null +++ b/src/Radiosender/Services/SettingsStore.cs @@ -0,0 +1,31 @@ +namespace Radiosender.Services; + +/// +/// The current for the whole app. Loads them at startup and, on every save, +/// writes the file and hands the minutes per hour to the schedule generator. +/// +public class SettingsStore +{ + private readonly ScheduleGenerator _generator; + private readonly string _path; + + public SettingsStore(ScheduleGenerator generator, string path) + { + _generator = generator; + _path = path; + Current = AppSettings.Load(path); + _generator.Options = Current.ToScheduleOptions(); + } + + public AppSettings Current { get; private set; } + + /// Stores the settings and applies them: alerts at once, minutes per hour from the next plan on. + /// The settings file cannot be written. + /// The settings file cannot be written. + public void Save(AppSettings settings) + { + settings.Save(_path); + Current = settings; + _generator.Options = settings.ToScheduleOptions(); + } +} diff --git a/src/Radiosender/Views/MainWindow.xaml.cs b/src/Radiosender/Views/MainWindow.xaml.cs index 1792a4e..3c42ffa 100644 --- a/src/Radiosender/Views/MainWindow.xaml.cs +++ b/src/Radiosender/Views/MainWindow.xaml.cs @@ -1,7 +1,9 @@ using System.Windows.Threading; using NAudio.Wave; using NAudio.Wave.SampleProviders; +using Radiosender.Controllers; using Radiosender.Models; +using Radiosender.Services; using Radiosender.Views.Pages; using Wpf.Ui.Controls; @@ -10,11 +12,17 @@ namespace Radiosender.Views; public partial class MainWindow : FluentWindow { private readonly DispatcherTimer _reminderTimer = new() { Interval = TimeSpan.FromSeconds(1) }; + private readonly ScheduleController _schedule; + private readonly SettingsStore _settings; private DateTime _remindedFor; - public MainWindow() + public MainWindow(IServiceProvider services, ScheduleController schedule, SettingsStore settings) { + _schedule = schedule; + _settings = settings; InitializeComponent(); + // The navigation view asks the container for each page, so pages get their controllers injected. + RootNavigation.SetServiceProvider(services); // Re-themes the app when the user switches the Windows theme while it runs. Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this); Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage)); @@ -25,10 +33,10 @@ public partial class MainWindow : FluentWindow // Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up. private void RemindSpeaker() { - var settings = App.Settings; + var settings = _settings.Current; TimeSpan? newsLead = settings.NewsAlert ? TimeSpan.FromSeconds(settings.NewsAlertSeconds) : null; TimeSpan? moderatorLead = settings.ModeratorAlert ? TimeSpan.FromSeconds(settings.ModeratorAlertSeconds) : null; - if (App.Schedule.UpcomingSpeech(newsLead, moderatorLead) is not { } item || item.Start == _remindedFor) + if (_schedule.UpcomingSpeech(newsLead, moderatorLead) is not { } item || item.Start == _remindedFor) return; _remindedFor = item.Start; // once per item var isNews = item.Kind == ScheduleItemKind.News; diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs index ff45ae7..68657a7 100644 --- a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs +++ b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs @@ -9,9 +9,13 @@ namespace Radiosender.Views.Pages; public partial class LibraryPage : Page { - private readonly LibraryController _controller = new(App.Songs); + private readonly LibraryController _controller; - public LibraryPage() => InitializeComponent(); + public LibraryPage(LibraryController controller) + { + _controller = controller; + InitializeComponent(); + } private Song? Selected => SongList.SelectedItem as Song; diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs index a0cd37a..14bca91 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs @@ -11,7 +11,7 @@ namespace Radiosender.Views.Pages; public partial class SchedulePage : Page { - private readonly ScheduleController _controller = App.Schedule; + private readonly ScheduleController _controller; private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) }; private bool _loading; private int _scrolledTo = -1; @@ -29,8 +29,9 @@ public partial class SchedulePage : Page // Optimistic state: what the user just asked for, shown before the engine has caught up. private bool? _expectPlaying; - public SchedulePage() + public SchedulePage(ScheduleController controller) { + _controller = controller; InitializeComponent(); Timeline.ItemsSource = _rows; // Also refreshes the buttons: Finished can arrive just before the engine reports it stopped. diff --git a/src/Radiosender/Views/Pages/SettingsPage.xaml.cs b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs index a3cb375..030efe0 100644 --- a/src/Radiosender/Views/Pages/SettingsPage.xaml.cs +++ b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs @@ -9,10 +9,16 @@ namespace Radiosender.Views.Pages; /// Edits . Nothing changes until Save. public partial class SettingsPage : Page { - public SettingsPage() => InitializeComponent(); + private readonly SettingsStore _store; + + public SettingsPage(SettingsStore store) + { + _store = store; + InitializeComponent(); + } // Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped. - private void OnLoaded(object sender, RoutedEventArgs e) => Show(App.Settings); + private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current); private void Show(AppSettings settings) { @@ -54,7 +60,7 @@ public partial class SettingsPage : Page try { - App.SaveSettings(settings); + _store.Save(settings); ShowMessage(InfoBarSeverity.Success, "Gespeichert", "Minuten pro Stunde gelten für den nächsten Plan."); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)