0

I currently have the call to my file io class in the constructor of my controller class of my project. I noticed the csv file gets re-read every time I hit the api endpoint, which is not ideal. Where should I have this so my csv only gets read in on startup?

namespace API.Controllers
{
    [ApiController]

    public class CovidDataController : ControllerBase
    {
        private ReadCSV readCSV;

        public CovidDataController()
        {
            readCSV = new ReadCSV("CovidFileIO/covid19-download.csv");
            readCSV.CreateDataObjects(100); // Pass in how many lines to read
        }

        // This endpoint will return records from the covid data object.
        [Route("api/[controller]")] // route is api/CovidData
        [HttpGet]
        public List<CovidData> GetData()
        {
            return readCSV.covidDataObjects;
        }
    }
}
Andy
  • 12,859
  • 5
  • 41
  • 56
karlrez
  • 61
  • 5
  • 1
    Why not make data static? – konzo Feb 03 '21 at 05:21
  • This is ASP.NET Core. Not ASP.NET. You need to create a DI service. Controllers should do controller things. Loading data is not a controller thing, it's a data layer thing. Don't put static vars in a controller either. Look up Dependency Injection for ASP.NET Core. – Andy Feb 03 '21 at 05:38
  • 1
    You have tons of options to consider. But the best way, in my view, is to read it in `ConfigureServices` method inside `Startup` class. It's a common way to read config files in .Net core. – Muhammad Vakili Feb 03 '21 at 05:42
  • What type covidDataObjects is? I need it to show you how to inject it into CovidDataController constructor – Jesús López Feb 03 '21 at 05:45
  • Another option is to just make a simple static class wherever you wish and inside that, check if you've already read data from IO or not. You won't lose the data either way. – Muhammad Vakili Feb 03 '21 at 05:47
  • You can even use cache in this case. just take a look at this: https://sahansera.dev/in-memory-caching-aspcore-dotnet/ – Muhammad Vakili Feb 03 '21 at 05:48
  • @Andy. I agree with you. most of the time having lots of options means you don't know the right decision. Having a layer for managing this is absolutely the rightest way, of course, I know. I just thought that he's not going to create that much big stuff. My bad, I should've asked him. – Muhammad Vakili Feb 03 '21 at 06:05

1 Answers1

0

You can create a middleware and then register in startup.cs it will run only when the website if hit on the url only once

your middleware code

//create Middleware folder

public task CSVMiddleware(){

  private ReadCSV readCSV;

            readCSV = new ReadCSV("CovidFileIO/covid19-download.csv");
            readCSV.CreateDataObjects(100); // Pass in how many lines to read
            return readCSV.covidDataObjects;

   }
}

and You can do this in startup.cs

app.Run(CSVMiddleware);
Asad
  • 617
  • 2
  • 8
  • 23