skip to Main Content

I start learning asp.net core MVC for practice purposes I created one HomeController in which I have two methods

     [Route("[controller]/[action]")]
     public class HomeController : Controller
     {
        private readonly JobRepository _jobRepository;
        public HomeController()
        {
            _jobRepository = new JobRepository();
        }

        [HttpPost]
        public IActionResult AddJob(int job)
        {
            return Ok(_jobRepository.AddJob(job));
        }

        [HttpGet]
        public IActionResult GetAllJobs()
        {
            return Ok(_jobRepository.GetAllJobs());
        }

    }

I am receiving data in my controller but the problem is when the data is transferred to my repository where I am saving all the Jobs in the int list

public class JobRepository
    {
        List<int> jobs  = new List<int>();

        public int AddJob(int job)
        {
            jobs.Add(job);
            return job;
        }

        public List<int> GetAllJobs()
        {
            return jobs;
        }
    }

The data is entered in the list but when I do another hit on my controller my list is reinitialized and the list count shows 1 in the immediate window

2

Answers


  1. Each time you enter JobRepository it creates a new object of the List so it will be empty
    If you want to store it temporally then make the object as static to avoid creating a new object each time

    If you want persistence you may want to use database and entityframework
    Refer for documentation

    https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-6.0

    Login or Signup to reply.
  2. public HomeController()
    {
    // This instantiates a new instance of JobController,
    // it >>does not<< inject one from DI.
        _jobRepository = new JobRepository();
    }
    

    This ignores your DI registration settings.

    Instead do:

    // Assuming JobRepository implements IJobRepository (which it should) 
    // and it is registered in DI as 
    // services.AddSingleton<IJobRepository, JobRepository>();
    public HomeController( IJobRepository jobRepository )
    {
        _jobRepository = jobRepository;
    }
    

    or without interface (which I wouldn’t recommend):

    public HomeController( JobRepository jobRepository )
    {
        _jobRepository = jobRepository;
    }
    

    unrelated, I’d also recommend to add the null check

    public HomeController( JobRepository jobRepository )
    {
        _jobRepository = jobRepository ?? throw new ArgumentNullException(nameof(jobRepository));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search