lundi 28 mai 2018

Checking additional static properties on lazy singleton pattern (Jon Skeet singleton)

I'm implementing Jon Skeet's Singleton using System.Lazy<T>.

My singleton differs slightly though. My singleton class represents the configuration of one of my services, and that service has a connection to a database. I have an additional readonly static property that returns true if my service is disconnected.

I did this by checking the IsValueCreated property on the lazy object first, and calling Value if it has not been created to ensure that when I check my ConnectionString property, my singleton has been instantiated.

Is there a more elegant way of implementing Disconnected? Is disconnected thread safe in this current implementation (without locks)? Any insight would be greatly appreciated.

Example code below:

    public sealed class MyServiceConfiguration {
        private static Lazy<MyServiceConfiguration> lazy = new Lazy<MyServiceConfiguration>(() => new MyServiceConfiguration());

        private static string ConnectionString = "";

        public static MyServiceConfiguration Instance { get { return lazy.Value; } }

        public static bool Disconnected {
            get {
                if (!lazy.IsValueCreated) { lazy.Value; }
                return ConnectionString == "";
            }
        }

        private MyServiceConfiguration() {
            //...additional service configuration options...
            ConnectionString = "someConnectionString";
        }
    }

Aucun commentaire:

Enregistrer un commentaire