Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing singleton instead of a global static instance
    primarykey
    data
    text
    <p>I ran into a problem today and a friend recommended I use a global static instance or more elegantly a singleton pattern. I spent a few hours reading about singletons but a few things still escape me.</p> <p>Background: What Im trying to accomplish is creating an instance of an API and use this one instance in all my classes (as opposed to making a new connection, etc).</p> <p>There seems to be about 100 ways of creating a singleton but with some help from <a href="http://www.yoda.arachsys.com/csharp/singleton.html" rel="noreferrer" title="aka Jon Skeet">yoda</a> I found some thread safe examples. ..so given the following code:</p> <pre><code>public sealed class Singleton { public static Singleton Instance { get; private set; } private Singleton() { APIClass api = new APIClass(); //Can this be done? } static Singleton() { Instance = new Singleton(); } } </code></pre> <p>How/Where would you instantiate the this new class and how should it be called from a separate class?</p> <p>EDIT: I realize the Singleton class can be called with something like</p> <pre><code>Singleton obj1 = Singleton.Instance(); </code></pre> <p>but would I be able to access the methods within the APIs Class (ie. obj1.Start)? (not that I need to, just asking)</p> <p>EDIT #2: I might have been a bit premature in checking the answer but I do have one small thing that is still causing me problems. The API is launching just fine, unfortunately Im able to launch two instances?</p> <p>New Code</p> <pre><code>public sealed class SingletonAPI { public static SingletonAPI Instance { get; private set; } private SingletonAPI() {} static SingletonAPI() { Instance = new SingletonAPI(); } // API method: public void Start() { API myAPI = new API();} } </code></pre> <p>but if I try to do something like this...</p> <pre><code>SingletonAPI api = SingletonAPI.Instance; api.Start(); SingletonAPI api2 = SingletonAPI.Instance; // This was just for testing. api2.Start(); </code></pre> <p>I get an error saying that I cannot start more than one instance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload