Controller methods share common data

2033

Member
Joined
May 11, 2025
Messages
17
Programming Experience
1-3
@Skydiver, did it the other way; now it's better. Thanks.

I wanted to solve one problem a long time ago, but I lack experience in programming, so I'll ask here.

In my home controller, I have two methods. As you can see, they share some data between them. (_set and _currentWord - static fields). Did it in order to not ask DB to bring data all the time. But I heard that having static fields is not a good idea in an ASP app. Maybe you have something in mind with your experience on how I can avoid them and not bother DB every time.

Because the SwitchWord method is called pretty often, it's not an option to get set from DB every time.

StudySelectedSet, on the other hand, is called to render an entire view, so it's not a big deal to fetch some data in this method.

C#:
[HttpGet]
public async Task<IActionResult> StudySelectedSet(int id)
{
    if (id is 0)
        return BadRequest();

    _set = mapper.Map<SetViewModel>(await dataManager.SetRepository.GetAsync(id));

    if (_set is null)
        return NotFound();

    _currentWord.Count = _set.Words.Count;
    _currentWord.CurrentWord = _set.Words[0];

    return View(_currentWord);
}

[HttpGet]
public IActionResult SwitchWord(int index = 0)
{
    if (index < 0 || index >= _set.Words.Count)
    {
        return NotFound();
    }
    return Json(_set.Words[index]);
}
 
Static field should only be used for practically constant data. Using the static field to communicate information from one instance of a object, to another instance can be rife with problems. Recall the lifecycle of a controller: a new instance is created for every web request.

What do you do if your web app is running on two servers, and the first request goes to server 1, and the second request goes to server 2?

What do you do if your web app is running on one server, but there are two users, and both of you make the StudySelectedSet() with your request coming in first, and the other person's coming in second, and then follow up with the call to SwitchWord() coming from the other person first, and then you second?

In general, making use of session state that travels with the user is the way to get around issues like this. Others use caching to speed up their database queries. Others use a faster "in-memory" database as a front end for the more durable but slower database. Some opt for a faster NoSQL solution. It really depends on the problem you are trying to solve.
 
You should probably be using session variables. Session variables are persisted across requests and they are also per user, so they allow different users to have their own persistent values.
 
Back
Top Bottom