I need to get a list of stations(lazily) from a remote service and to store it in DB and in memory.
Then, if someone wants the list, he tries to read the in memory list.
If it's null , it goes to Db and if there's no data in DB , it should go to a remote service , fetch the list , and to store the list in DB and in memory.
(Basically, I don't want to go to the remote service every request)
So I've used the .net core's singleton service :
services.AddSingleton<IStations,Stations>()
Where the class will contain the list itself :
public class Stations:IStations
{
public List<StationModel> LstStationModel
{
get
{
lock (locker)
{
if (_lstStationModel == null)
{
var ls = GetStationsFromDb().Result;
if (ls!=null && ls.Count > 0)
_lstStationModel = ls;
else
_lstStationModel = GetStationsFromProvider().Result;
}
return _lstStationModel;
}
}
set
{
lock (locker)
{
_lstStationModel = value;
}
}
}
}
So now I have a single property in a singleton class .
When someone asks for the list , I check if it's null , then I go to db. If the db doesn't have the data , I start fetching from remote and fill the list.
I've also added lock , so that 2 requests won't invoke fetching twice.
Question
Something here doesn't look right. I was forced to use .Result
rather than async await. I wantd to do it with property to have get
and set
. But I'm not sure it's the right way of dong it. And besides , I really don't like this solution.
Is there any way to do it in a more elegant/better way ?
Aucun commentaire:
Enregistrer un commentaire