maui icon indicating copy to clipboard operation
maui copied to clipboard

iOS singleton dependency injection wrong lifecycle

Open pwsjvermeulen opened this issue 1 year ago • 1 comments

Description

I'm using an AppContext class which is registered as singleton in the dependency container of my application. When running on Android, this context is the same object across every page and view model. This is not the case when running the application on iOS.

I have tested this by creating an empty constructor and placing a breakpoint in here. The constructor is called when first initialized. When I navigate to the second page where this context is used, the constructor is again called on iOS. This is behaviour does not happen on Android.

Steps to Reproduce

  1. Register a class as singleton.
  2. Create two pages, add the singleton as argument to the constructor of both these pages.
  3. Navigate from one page to the other.

Link to public reproduction project repository

No response

Version with bug

8.0.82 SR8.2

Is this a regression from previous behavior?

Not sure, did not test other versions

Last version that worked well

Unknown/Other

Affected platforms

iOS

Affected platform versions

iOS 15.5, iOS 17.2

Did you find any workaround?

I'm currently using a overload of the AddSingleton method which takes a Func as argument. This function is used to get the instance of the context by using a static Instance property.

public class AppContext {
  private static AppContext _instance;
       
  public static AppContextInstance
  {
    get => _instance ??= new AppContext();
  }
}

The overload method:

builder.Services.AddSingleton<AppContext, AppContext>(item => AppContext.Instance);

Relevant log output

No response

pwsjvermeulen avatar Oct 24 '24 13:10 pwsjvermeulen

I couldn't get it reproduced in a new project. I do not have the time now the add a repro but will add one later today or tomorrow... Probably will do that on another account as well.

pwsjvermeulen avatar Oct 25 '24 06:10 pwsjvermeulen

The Dependency Injection being used here is Microsoft.Extensions.DependencyInjection. MAUI, AFAIK, doesn't influence this nor rolls its own. How are you navigating pages? Are you using Shell?

drasticactions avatar Oct 29 '24 06:10 drasticactions

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.