jeudi 27 juillet 2017

c#: how to implement singleton pattern to return client that should be initialised just once in application life cycle?

Currently, we are initialising elastic search client. We want to initialise ElasticClient just once in our application and re-use it to avoid unnecessary initialisation every time we make elastic search call.

The code looks like:

public sealed class ElasticClientInstance
{
    private static readonly ElasticClientInstance _clientInstance = new ElasticClientInstance();

    private ElasticClient _client;

    static ElasticClientInstance () {

    }

    public static ElasticClient GetInstance() {
        return _clientInstance._client;
    }

    private ElasticClientInstance()
    {
        try
        {
             Uri[] nodes = ConfigurationManager.AppSettings["ElasticHostUrl"].Split(';')
                            .Select(s => new Uri("http://" + s)).ToArray();
            var connectionPool = new SniffingConnectionPool(nodes);
            var settings = new ConnectionSettings(...); //some code not mentioned here
            _client = new ElasticClient(settings);
        }
        catch (Exception ex) 
        {
            //do necessary handling
        }

    }
}

Anytime we need elastic client, we do ElasticClient.GetInstance(). Is it the correct way to make this client singleton?

I read that initialising "_clientInstance" as readonly makes it thread safe? Is this performance oriented and safe implementation of singleton pattern?

Aucun commentaire:

Enregistrer un commentaire