Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 75885

The dangers of using singletons in Xamarin.Forms App constructor

$
0
0

Hi, I was not sure where to post this but Xamarin Forms forum seems to be the best fit.

I wanted to share an unpleasant experience, in order to help people who might (and will) encounter this issue.

1/ Problem

For the app I'm building, I was using the excellent MVVM Light example that Laurent shared with us at Evolve (with latest stable Xamarin.Forms package). However, I encountered several times an exception on the registering of my services when I was closing and reopening an application on Android : services were already registered, thus crashing the application with an InvalidOperationException : This is already a factory registered for XXX.

2/ Conditions

What I was doing was the initialization of the SimpleIoc, and the registering of my services on the constructor of my Xamarin.Forms App, just as Laurent did. While this seems a good approach, it hides an underlying problem that might be quite counter-intuitive.

3/ Explanations

Bascially, when closing an App on Android, it is not terminated. So when you launch it again a short time after, you just re-create the application within the same context. To make it clearer : your Xamarin.Forms.Application lifecycle is NOT your application lifecycle.

So this implies that you might actually have to get several times trough OnCreate, and several times through the constructor of your Xamarin.Forms App. But with an initialization of a singleton in the constructor, you will encounter problems.

4/ Fix

There is many possibilities to treat that issue, the most elegant I found was to keep a reference to the Xamarin.Forms App and call an App.Clean() method (to reset the SimpleIoc) on the OnDestroy() of Android. According to Xamarin Android Lifecycle, this is enough.

5/ Conclusion

Attached, a sample project demonstrating the issue and the fix. Please note that I wasn't able to test on iOS or Windows Phone, I don't know if you might encounter a similar problem. I'm open to suggestions and feedbacks !

With this tricky thing, I wonder if this « Clean » (onDestroy ?) of Xamarin.Forms Application should not be implemented by default (and called accordingly by Android.OnDestroy()).

Thanks

I want to thank Xamarin.Insights and Laurent for the finding and explanations of this issue.

Please feel free to react, interact and criticize the topic and / or the solution.


Viewing all articles
Browse latest Browse all 75885

Trending Articles