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 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 15:09:35 +01:00
1 parent 65743279b1
commit c6e9bf4e82
9 files changed
+112 -35

No files matched your search

+1 -2
View File
@@ -1,8 +1,7 @@
<Application x:Class="Radiosender.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
StartupUri="Views/MainWindow.xaml">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
+49 -22
View File
@@ -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;
/// <summary>Composition root: wires every service, controller and page once, at startup.</summary>
public partial class App : Application
{
public static SongRepository Songs { get; private set; } = null!;
private ServiceProvider? _services;
/// <summary>App-wide, so a running broadcast keeps going while the user switches pages.</summary>
public static ScheduleController Schedule { get; private set; } = null!;
public static AppSettings Settings { get; private set; } = new();
private static readonly ScheduleGenerator Generator = new();
/// <summary>Stores the settings and applies them: alerts at once, minutes per hour from the next plan on.</summary>
/// <exception cref="System.IO.IOException">The settings file cannot be written.</exception>
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception>
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<ScheduleGenerator>(), AppSettings.DefaultPath));
services.AddSingleton(_ => new PlaybackEngine());
services.AddSingleton(provider => new ScheduleController(
provider.GetRequiredService<SongRepository>(),
provider.GetRequiredService<ScheduleGenerator>(),
provider.GetRequiredService<PlaybackEngine>(),
() => 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<IMusicProvider, OpenverseProvider>();
services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<System.Net.Http.HttpClient>(), TrackDownloader.DefaultMusicFolder));
services.AddSingleton<OnlineImportController>();
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory));
services.AddSingleton<UploadController>();
services.AddSingleton<LibraryController>();
// Pages are created anew on every navigation, as before; they hold only view state.
services.AddSingleton<MainWindow>();
services.AddTransient<SchedulePage>();
services.AddTransient<LibraryPage>();
services.AddTransient<ImportPage>();
services.AddTransient<SettingsPage>();
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<SettingsStore>();
// Follow the Windows setting: light, dark or a high-contrast theme.
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
base.OnStartup(e);
_services.GetRequiredService<MainWindow>().Show();
}
protected override void OnExit(ExitEventArgs e)
{
Schedule.Stop();
_services?.GetRequiredService<ScheduleController>().Stop();
_services?.Dispose();
base.OnExit(e);
}
}
@@ -5,7 +5,7 @@ namespace Radiosender.Controllers;
/// <summary>
/// Creates the broadcast plan and drives its playback. One instance lives for the whole app
/// (<see cref="App.Schedule"/>), so the plan survives page navigation.
/// (registered as a singleton in <see cref="App"/>), so the plan survives page navigation.
/// </summary>
/// <remarks>Events come from the playback engine's thread pool; views marshal with <c>Dispatcher.BeginInvoke</c>.</remarks>
public class ScheduleController
+1
View File
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.15" />
<PackageReference Include="NAudio" Version="3.3.0" />
<PackageReference Include="TagLibSharp" Version="2.3.0" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
+31
View File
@@ -0,0 +1,31 @@
namespace Radiosender.Services;
/// <summary>
/// The current <see cref="AppSettings"/> 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.
/// </summary>
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; }
/// <summary>Stores the settings and applies them: alerts at once, minutes per hour from the next plan on.</summary>
/// <exception cref="System.IO.IOException">The settings file cannot be written.</exception>
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception>
public void Save(AppSettings settings)
{
settings.Save(_path);
Current = settings;
_generator.Options = settings.ToScheduleOptions();
}
}
+11 -3
View File
@@ -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;
@@ -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;
@@ -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.
@@ -9,10 +9,16 @@ namespace Radiosender.Views.Pages;
/// <summary>Edits <see cref="AppSettings"/>. Nothing changes until Save.</summary>
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)