xamarin-forms-samples icon indicating copy to clipboard operation
xamarin-forms-samples copied to clipboard

Using Xamarin Dependency Service instead of Singleton Pattern

Open khaledbakeer opened this issue 4 years ago • 0 comments

Why do you use the Singleton Pattern hier:

https://github.com/xamarin/xamarin-forms-samples/blob/4fb8e8c9e5aa9c1b7c9438411d2826bc71940f27/LocalNotifications/LocalNotifications/LocalNotifications.Android/AlarmHandler.cs#L15

if you defined Xamarin.Forms Dependency Service hier: https://github.com/xamarin/xamarin-forms-samples/blob/4fb8e8c9e5aa9c1b7c9438411d2826bc71940f27/LocalNotifications/LocalNotifications/LocalNotifications.Android/AndroidNotificationManager.cs#L10

So I think we could use:

// this:
var manager = DependencyService.Get<AndroidNotificationManager>();
// instead of this:
AndroidNotificationManager manager = AndroidNotificationManager.Instance ?? new AndroidNotificationManager();

and we can then remove the static instance in AndroidNotificationManager.cs:

https://github.com/xamarin/xamarin-forms-samples/blob/4fb8e8c9e5aa9c1b7c9438411d2826bc71940f27/LocalNotifications/LocalNotifications/LocalNotifications.Android/AndroidNotificationManager.cs#L30

because it could be generate two instances, one from the static one and another from Xamarin Dip. Service, what you need to avoid in you example.

khaledbakeer avatar Apr 13 '21 08:04 khaledbakeer