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 :)
1 Answer 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.
JsonLoader
implementingIJsonloader
? 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 ofJsonLoader
and inject that into the parts of your code (via references toIJsonloader
, that need access to it.