1

I have JSON file which has some hundereds of rows stored like below..

[
  {
    "Id": "1",
    "Name": "A"
  },
  {
    "Id": "1",
    "Name": "A"
  }
]

I am trying to load this into collection of a class. This data is static and wont change, so I need to load this only once.

I have created a class and loading this in private constructor and loading into collection that I have in the class.

    public sealed class JsonLoader : IJsonloader
    {
        private readonly IEnumerable<Product> products = new List<Product>();

        private JsonLoader()
        {
            using (var r = new StreamReader("data.json"))
            {
                var json = r.ReadToEnd();
                products = //deserialse the json here 
            }
        }

        public static IEnumerable<Product> Products => this.products;
    }

Implement singleton using structure map singleton option. I want to know if my way of implementation is correct or if this can improved any further?

or Any other best way to do it? any help much appreciated :)

  • 2
    What's the point of JsonLoader implementing IJsonloader? You are creating a singleton, assessable only via a service locator, meaning there's no way to test the way other code interacts with it via a mock. Simple answer to you question: don't use the singleton or service locator anti-patterns. Create a single instance of JsonLoader and inject that into the parts of your code (via references to IJsonloader, that need access to it. – David Arno Jul 26 '16 at 9:00
  • 1. It's hard to review code this small, especially if it's incomplete. 2. If you're looking for a code review, there is a dedicated site for that: codereview.stackexchange.com, but you should post your actual code there. – svick Jul 26 '16 at 12:32
-1

Make your loader static and put your load function in the static constructor. Then when the static constructor is called the list will be loaded and essentially cached in the static list until the application is unloaded. This will ensure your data is loaded once since static constructors are thread safe.

For testing proposes you could put an interface that wraps the static loader to mock the list of products if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.