Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code Quality: Replace static instance in App with DI #13382

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/Files.App/Actions/Favorites/PinItemAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ namespace Files.App.Actions
{
internal class PinItemAction : ObservableObject, IAction
{
private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();

private readonly IContentPageContext context;

private readonly IQuickAccessService service;
Expand All @@ -31,7 +33,7 @@ public PinItemAction()
service = Ioc.Default.GetRequiredService<IQuickAccessService>();

context.PropertyChanged += Context_PropertyChanged;
App.QuickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged;
_quickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged;
}

public async Task ExecuteAsync()
Expand All @@ -50,7 +52,7 @@ public async Task ExecuteAsync()

private bool GetIsExecutable()
{
string[] favorites = App.QuickAccessManager.Model.FavoriteItems.ToArray();
string[] favorites = _quickAccessManager.Model.FavoriteItems.ToArray();

return context.HasSelection
? context.SelectedItems.All(IsPinnable)
Expand Down
6 changes: 4 additions & 2 deletions src/Files.App/Actions/Favorites/UnpinItemAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ namespace Files.App.Actions
{
internal class UnpinItemAction : ObservableObject, IAction
{
private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();

private readonly IContentPageContext context;

private readonly IQuickAccessService service;
Expand All @@ -30,7 +32,7 @@ public UnpinItemAction()
service = Ioc.Default.GetRequiredService<IQuickAccessService>();

context.PropertyChanged += Context_PropertyChanged;
App.QuickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged;
_quickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged;
}

public async Task ExecuteAsync()
Expand All @@ -48,7 +50,7 @@ public async Task ExecuteAsync()

private bool GetIsExecutable()
{
string[] favorites = App.QuickAccessManager.Model.FavoriteItems.ToArray();
string[] favorites = _quickAccessManager.Model.FavoriteItems.ToArray();

return context.HasSelection
? context.SelectedItems.All(IsPinned)
Expand Down
6 changes: 4 additions & 2 deletions src/Files.App/Actions/FileSystem/PasteItemAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ namespace Files.App.Actions
{
internal class PasteItemAction : ObservableObject, IAction
{
private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>();

private readonly IContentPageContext context;

public string Label
Expand All @@ -35,7 +37,7 @@ public PasteItemAction()
context = Ioc.Default.GetRequiredService<IContentPageContext>();

context.PropertyChanged += Context_PropertyChanged;
App.AppModel.PropertyChanged += AppModel_PropertyChanged;
_appModel.PropertyChanged += AppModel_PropertyChanged;
}

public async Task ExecuteAsync()
Expand All @@ -50,7 +52,7 @@ public async Task ExecuteAsync()
public bool GetIsExecutable()
{
return
App.AppModel.IsPasteEnabled &&
_appModel.IsPasteEnabled &&
context.PageType != ContentPageTypes.Home &&
context.PageType != ContentPageTypes.RecycleBin &&
context.PageType != ContentPageTypes.SearchResults;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace Files.App.Actions
{
internal class PasteItemToSelectionAction : BaseUIAction, IAction
{
private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>();

private readonly IContentPageContext context;

public string Label
Expand All @@ -27,7 +29,7 @@ public PasteItemToSelectionAction()
context = Ioc.Default.GetRequiredService<IContentPageContext>();

context.PropertyChanged += Context_PropertyChanged;
App.AppModel.PropertyChanged += AppModel_PropertyChanged;
_appModel.PropertyChanged += AppModel_PropertyChanged;
}

public async Task ExecuteAsync()
Expand All @@ -44,7 +46,7 @@ public async Task ExecuteAsync()

public bool GetIsExecutable()
{
if (!App.AppModel.IsPasteEnabled)
if (!_appModel.IsPasteEnabled)
return false;

if (context.PageType is ContentPageTypes.Home or ContentPageTypes.RecycleBin or ContentPageTypes.SearchResults)
Expand Down
4 changes: 3 additions & 1 deletion src/Files.App/Actions/Navigation/NextTabAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace Files.App.Actions
{
internal class NextTabAction : ObservableObject, IAction
{
private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>();

private readonly IMultitaskingContext multitaskingContext;

public string Label
Expand All @@ -28,7 +30,7 @@ public NextTabAction()

public Task ExecuteAsync()
{
App.AppModel.TabStripSelectedIndex = (App.AppModel.TabStripSelectedIndex + 1) % multitaskingContext.TabCount;
_appModel.TabStripSelectedIndex = (_appModel.TabStripSelectedIndex + 1) % multitaskingContext.TabCount;

return Task.CompletedTask;
}
Expand Down
8 changes: 5 additions & 3 deletions src/Files.App/Actions/Navigation/PreviousTabAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace Files.App.Actions
{
internal class PreviousTabAction : ObservableObject, IAction
{
private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>();

private readonly IMultitaskingContext multitaskingContext;

public string Label
Expand All @@ -28,10 +30,10 @@ public PreviousTabAction()

public Task ExecuteAsync()
{
if (App.AppModel.TabStripSelectedIndex is 0)
App.AppModel.TabStripSelectedIndex = multitaskingContext.TabCount - 1;
if (_appModel.TabStripSelectedIndex is 0)
_appModel.TabStripSelectedIndex = multitaskingContext.TabCount - 1;
else
App.AppModel.TabStripSelectedIndex--;
_appModel.TabStripSelectedIndex--;

return Task.CompletedTask;
}
Expand Down
63 changes: 36 additions & 27 deletions src/Files.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,21 @@ namespace Files.App
{
public partial class App : Application
{
private IHost? _host;
private static bool _showErrorNotification;
private static QuickAccessManager _quickAccessManager;
private static AppModel _appModel;

private static bool ShowErrorNotification = false;
public static string OutputPath { get; set; }
public static string? OutputPath { get; set; }
public static CommandBarFlyout? LastOpenedFlyout { get; set; }
public static TaskCompletionSource? SplashScreenLoadingTCS { get; private set; }

public static StorageHistoryWrapper HistoryWrapper { get; } = new();
public static AppModel AppModel { get; private set; }
public static RecentItems RecentItemsManager { get; private set; }
public static QuickAccessManager QuickAccessManager { get; private set; }
// TODO: Remove below properties
public static CloudDrivesManager CloudDrivesManager { get; private set; }
public static WSLDistroManager WSLDistroManager { get; private set; }
public static LibraryManager LibraryManager { get; private set; }
public static FileTagsManager FileTagsManager { get; private set; }

public static SecondaryTileHelper SecondaryTileHelper { get; private set; }
public static ILogger Logger { get; private set; }
public static SecondaryTileHelper SecondaryTileHelper { get; private set; } = new();

/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
Expand Down Expand Up @@ -96,6 +93,17 @@ private IHost ConfigureHost()
.AddProvider(new FileLoggerProvider(Path.Combine(ApplicationData.Current.LocalFolder.Path, "debug.log")))
.SetMinimumLevel(LogLevel.Information))
.ConfigureServices(services => services
// Transient managers
.AddTransient<StorageHistoryWrapper>()
.AddTransient<AppModel>()
.AddTransient<RecentItems>()
.AddTransient<QuickAccessManager>()
.AddTransient<CloudDrivesManager>()
.AddTransient<WSLDistroManager>()
.AddTransient<LibraryManager>()
.AddTransient<FileTagsManager>()
.AddTransient<SecondaryTileHelper>()
// Generic services
.AddSingleton<IUserSettingsService, UserSettingsService>()
.AddSingleton<IAppearanceSettingsService, AppearanceSettingsService>(sp => new AppearanceSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext()))
.AddSingleton<IGeneralSettingsService, GeneralSettingsService>(sp => new GeneralSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext()))
Expand All @@ -105,12 +113,14 @@ private IHost ConfigureHost()
.AddSingleton<ILayoutSettingsService, LayoutSettingsService>(sp => new LayoutSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext()))
.AddSingleton<IAppSettingsService, AppSettingsService>(sp => new AppSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext()))
.AddSingleton<IFileTagsSettingsService, FileTagsSettingsService>()
// Contexts
.AddSingleton<IPageContext, PageContext>()
.AddSingleton<IContentPageContext, ContentPageContext>()
.AddSingleton<IDisplayPageContext, DisplayPageContext>()
.AddSingleton<IWindowContext, WindowContext>()
.AddSingleton<IMultitaskingContext, MultitaskingContext>()
.AddSingleton<ITagsContext, TagsContext>()
// Services
.AddSingleton<IDialogService, DialogService>()
.AddSingleton<IImageService, ImagingService>()
.AddSingleton<IThreadingService, ThreadingService>()
Expand Down Expand Up @@ -167,7 +177,7 @@ await Task.WhenAll(
LibraryManager.UpdateLibrariesAsync(),
OptionalTask(WSLDistroManager.UpdateDrivesAsync(), generalSettingsService.ShowWslSection),
OptionalTask(FileTagsManager.UpdateFileTagsAsync(), generalSettingsService.ShowFileTagsSection),
QuickAccessManager.InitializeAsync()
_quickAccessManager.InitializeAsync()
);

await Task.WhenAll(
Expand Down Expand Up @@ -225,13 +235,12 @@ async Task ActivateAsync()
SystemInformation.Instance.TrackAppUse(activationEventArgs);

// Configure Host and IoC
_host = ConfigureHost();
Ioc.Default.ConfigureServices(_host.Services);
var host = ConfigureHost();
Ioc.Default.ConfigureServices(host.Services);

// NOTE: Must ensure after configured DI container
EnsureSettingsAndConfigurationAreBootstrapped();

// TODO: Remove App.Logger instance and replace with DI
Logger = Ioc.Default.GetRequiredService<ILogger<App>>();
Logger.LogInformation($"App launched. Launch args type: {appActivationArguments.Data.GetType().Name}");

// Wait for the UI to update
Expand All @@ -246,15 +255,15 @@ async Task ActivateAsync()

private static void EnsureSettingsAndConfigurationAreBootstrapped()
{
// TODO(s): Remove initialization here and move out all classes (visible below) out of App.xaml.cs

RecentItemsManager ??= new RecentItems();
AppModel ??= new AppModel();
LibraryManager ??= new LibraryManager();
CloudDrivesManager ??= new CloudDrivesManager();
WSLDistroManager ??= new WSLDistroManager();
FileTagsManager ??= new FileTagsManager();
QuickAccessManager ??= new QuickAccessManager();
_quickAccessManager ??= Ioc.Default.GetRequiredService<QuickAccessManager>();
_appModel ??= Ioc.Default.GetRequiredService<AppModel>();

LibraryManager ??= Ioc.Default.GetRequiredService<LibraryManager>();
CloudDrivesManager ??= Ioc.Default.GetRequiredService<CloudDrivesManager>();
WSLDistroManager ??= Ioc.Default.GetRequiredService<WSLDistroManager>();
FileTagsManager ??= Ioc.Default.GetRequiredService<FileTagsManager>();
SecondaryTileHelper ??= Ioc.Default.GetRequiredService<SecondaryTileHelper>();
Logger = Ioc.Default.GetRequiredService<ILogger<App>>();
}

private void EnsureSuperEarlyWindow()
Expand All @@ -276,7 +285,7 @@ private void Window_Activated(object sender, WindowActivatedEventArgs args)
if (args.WindowActivationState is not (WindowActivationState.CodeActivated or WindowActivationState.PointerActivated))
return;

ShowErrorNotification = true;
_showErrorNotification = true;
ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Process.GetCurrentProcess().Id;
}

Expand Down Expand Up @@ -308,7 +317,7 @@ private async void Window_Closed(object sender, WindowEventArgs args)
}

if (Ioc.Default.GetRequiredService<IUserSettingsService>().GeneralSettingsService.LeaveAppRunning &&
!AppModel.ForceProcessTermination &&
!_appModel.ForceProcessTermination &&
!Process.GetProcessesByName("Files").Any(x => x.Id != Process.GetCurrentProcess().Id))
{
// Close open content dialogs
Expand Down Expand Up @@ -379,7 +388,7 @@ await SafetyExtensions.IgnoreExceptions(async () =>

// Destroy cached properties windows
FilePropertiesHelpers.DestroyCachedWindows();
AppModel.IsMainWindowClosed = true;
_appModel.IsMainWindowClosed = true;

// Wait for ongoing file operations
FileOperationsHelpers.WaitForCompletion();
Expand Down Expand Up @@ -474,7 +483,7 @@ private static void AppUnhandledException(Exception? ex, bool shouldShowNotifica
SaveSessionTabs();
App.Logger.LogError(ex, ex.Message);

if (!ShowErrorNotification || !shouldShowNotification)
if (!_showErrorNotification || !shouldShowNotification)
return;

var toastContent = new ToastContent()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace Files.App.Data.Contexts
{
internal class MultitaskingContext : ObservableObject, IMultitaskingContext
{
private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>();

private bool isPopupOpen = false;

private IMultitaskingControl? control;
Expand All @@ -30,7 +32,7 @@ internal class MultitaskingContext : ObservableObject, IMultitaskingContext
public MultitaskingContext()
{
MainPageViewModel.AppInstances.CollectionChanged += AppInstances_CollectionChanged;
App.AppModel.PropertyChanged += AppModel_PropertyChanged;
_appModel.PropertyChanged += AppModel_PropertyChanged;
BaseMultitaskingControl.OnLoaded += BaseMultitaskingControl_OnLoaded;
HorizontalMultitaskingControl.SelectedTabItemChanged += HorizontalMultitaskingControl_SelectedTabItemChanged;
FocusManager.GotFocus += FocusManager_GotFocus;
Expand Down Expand Up @@ -86,7 +88,7 @@ private void UpdateTabCount()
}
private void UpdateCurrentTabIndex()
{
if (SetProperty(ref currentTabIndex, (ushort)App.AppModel.TabStripSelectedIndex, nameof(CurrentTabIndex)))
if (SetProperty(ref currentTabIndex, (ushort)_appModel.TabStripSelectedIndex, nameof(CurrentTabIndex)))
{
OnPropertyChanged(nameof(CurrentTabItem));
}
Expand Down
4 changes: 3 additions & 1 deletion src/Files.App/Data/Items/DriveItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ namespace Files.App.Data.Items
{
public class DriveItem : ObservableObject, INavigationControlItem, ILocatableFolder
{
private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();

private BitmapImage icon;
public BitmapImage Icon
{
Expand Down Expand Up @@ -52,7 +54,7 @@ public bool IsNetwork
=> Type == DriveType.Network;

public bool IsPinned
=> App.QuickAccessManager.Model.FavoriteItems.Contains(path);
=> _quickAccessManager.Model.FavoriteItems.Contains(path);

public string MaxSpaceText
=> MaxSpace.ToSizeString();
Expand Down
4 changes: 3 additions & 1 deletion src/Files.App/Data/Items/ListedItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ namespace Files.App.Utils
{
public class ListedItem : ObservableObject, IGroupableItem
{
private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();

protected static IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>();

protected static readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
Expand Down Expand Up @@ -372,7 +374,7 @@ public override string ToString()
public bool IsAlternateStream => this is AlternateStreamItem;
public bool IsGitItem => this is GitItem;
public virtual bool IsExecutable => FileExtensionHelpers.IsExecutableFile(ItemPath);
public bool IsPinned => App.QuickAccessManager.Model.FavoriteItems.Contains(itemPath);
public bool IsPinned => _quickAccessManager.Model.FavoriteItems.Contains(itemPath);
public bool IsDriveRoot => ItemPath == PathNormalization.GetPathRoot(ItemPath);
public bool IsElevated => CheckElevationRights();

Expand Down
4 changes: 3 additions & 1 deletion src/Files.App/Data/Items/LocationItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace Files.App.Data.Items
{
public class LocationItem : ObservableObject, INavigationControlItem
{
private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();

public BitmapImage icon;
public BitmapImage Icon
{
Expand Down Expand Up @@ -79,7 +81,7 @@ public bool IsExpanded

public bool IsInvalid { get; set; } = false;

public bool IsPinned => App.QuickAccessManager.Model.FavoriteItems.Contains(path);
public bool IsPinned => _quickAccessManager.Model.FavoriteItems.Contains(path);

public SectionType Section { get; set; }

Expand Down
Loading