1

I have a Xamarin forms app that is using dryioc for IoC. It seems all my services get disposed as soon as the view is out of scope

This is how I am registering the service in the app.cs

 protected override void RegisterTypes(IContainerRegistry containerRegistry)
 {
    
     containerRegistry.RegisterSingleton<IInboxService, InboxService>();;
 }

and I resolve it this way in the app.cs

               protected override void OnInitialized()
            {
                _started = DateTime.Now;
                InitializeComponent();
                InitializeAppSettings();
               Container.Resolve<ISyncService>().Init(new List<ISyncableService>
                {
                   Container.Resolve<IInboxService>()
                });
}

When I need to use it in a viewmodel I put it in the constructor like so.

  public class HomeViewModel {
     public HomeViewModel(InboxService inboxService) 
     {
    
     }
}

The singleton is respected but then it will dispose and create a new one when it needs it. Anyone else run into this ?

Xamarin Version: 5.0.0.2125
Prism Version: 8.1.97
LocIOS Version: 8.1.97

Micah Armantrout
  • 6,781
  • 4
  • 40
  • 66
  • This [case](https://stackoverflow.com/questions/46424751/avoid-singleton-repository-dryioc-when-using-dependency-injection) may provide you some help. The answer of it talks about disposable transient service. In addition, you can use the other IOC container such as the TinyIoCContainer which the [offical document](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/dependency-injection) recommends. – Liyun Zhang - MSFT Feb 03 '22 at 06:41
  • interesting case ill let you know it that helps ty ... the official documentation is from 2017 I don't see how thats going to help me in the long run – Micah Armantrout Feb 03 '22 at 14:38

1 Answers1

3

public HomeViewModel(InboxService inboxService)

This injects a concrete InboxService instance, which is independent of the registration of interfaces that it might implement. If you want your singleton, request an IInboxService:

public HomeViewModel(IInboxService inboxService)

I try to give a service implementing a certain interface a meaningful name that's more than just interface's name minus I, like DummyInboxService, TestInboxService, ImapInboxService, Pop3InboxService, RemoteInboxService... thus making clearer what the respective implementation actually does and helping finding these errors (most likely a typo anyway) early.

Haukinger
  • 10,420
  • 2
  • 15
  • 28