Colore icon indicating copy to clipboard operation
Colore copied to clipboard

"you should create your chroma instance once"

Open M1XT3NZ opened this issue 5 years ago • 2 comments

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

M1XT3NZ avatar Jan 15 '20 02:01 M1XT3NZ

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 :)

Sharparam avatar Jan 15 '20 13:01 Sharparam

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.

M1XT3NZ avatar Jan 15 '20 18:01 M1XT3NZ