chroma-sdk / Colore

A powerful C# library for Razer Chroma's SDK
https://chroma-sdk.github.io/Colore/
MIT License
146 stars 30 forks source link

"you should create your chroma instance once" #280

Open M1XT3NZ opened 4 years ago

M1XT3NZ commented 4 years ago

Hey, in Getting Started there is the sentence

For this reason, you should create your Chroma instance once at application startup and then use this instance for the remainder of your application's lifetime.

I don't see a way to just create the instance once and use it for the whole lifetime.

It could be that I'm skipping something really obvious. Hope you can help

Regards, Michael

Sharparam commented 4 years ago

This will depend on how your application is designed. Assuming version 6.0 of Colore (v5.2 has built-in singleton behaviour), you could have something like this:

internal static class MyColore
{
  private static IChroma _chroma;

  public static async Task<IChroma> GetInstanceAsync()
  {
    if (_chroma != null)
    {
      return _chroma;
    }

    // Or use CreateRestAsync() if you need/want the Chroma REST API.
    _chroma = await ColoreProvider.CreateNativeAsync();

    return _chroma;
  }
}

And then whenever you need the instance, you can retrieve it like this:

public static class Program
{
  public static async Task Main()
  {
    var chroma = await MyColore.GetInstanceAsync();

    // Do stuff with the IChroma instance in `chroma`
  }
}

This is known as the "singleton pattern". There's an article on C# in Depth that explains it in more detail.

Hopefully that points you in the right direction :)

M1XT3NZ commented 4 years ago

Oh, thank you. I actually never worked with a Singleton Pattern got me really confused.

Maybe it would be nice if this could even be put into the Getting Started Wiki page? For other People that maybe didn't understand it or never worked with it.

Have a nice day.