Creating a singleton with Dependency service, but no interface?

I have been doing a lot of James Montemagno Tutorials and his CoffeeApp one is confusing me a little
https://github.com/jamesmontemagno/app-coffeecups/blob/master/CoffeeCups.Shared/ViewModel/CoffeesViewModel.cs

He wants to create a singleton of the AzureService that connects to a SQL table database. Which makes sense, and something I want to do in my app. I want it to define the server connection once, so that I can query from it on any page I am at. But he creates the singleton by using Dependency Services.

AzureService azureService;
public CoffeesViewModel()
{
azureService = DependencyService.Get();
}
From my understanding Dependency Service is used to access platform specific features. Which in turn creates singleton by default. But in this example he is not calling anything in the Android or iOS project. AzureService is in the shared project. Plus This Link says that you should be puting an interface into the <> not a normal class.

I have seen other ways of creating Singletons, with using statics and seal classes like this link

But I have done both and they do not seem to work. Or, more likely I don't understand Singletons. I imagine them like I create it once and it lives in memory. And if I call any method from an Interface of the Singleton object I don't need to do
var _singleton = new Singleton();

Just so that I can do
ISingleton.PushAsync();

But that seems to be the case, because if I call any of the ISingleton methods in any page outside where I made the singleton it gives me this error
System.NullReferenceException: Object reference not set to an instance of an object.

Do I have to make a new instance of the singleton on every page I go to?

Best Answer

  • JohnButlerJohnButler US ✭✭
    Accepted Answer

    I got it.
    I cant use an Interface to interact with a singleton object. I thought I could since in my mind a Singleton is always there. But you have to access the static method Singleton.Instance() or whatever you call it, to actually talk to that instance. Darn

Answers

  • JohnButlerJohnButler USMember ✭✭
    Accepted Answer

    I got it.
    I cant use an Interface to interact with a singleton object. I thought I could since in my mind a Singleton is always there. But you have to access the static method Singleton.Instance() or whatever you call it, to actually talk to that instance. Darn

  • FotalFotal Member ✭✭✭

    @JohnButler Show please your code file for singleton class and how you invoke DependencyService

Sign In or Register to comment.