0

Can anyone guide me why I am only able to update the default state after every crud call and why the controller object is reinitialized every time before the call.

Here is my code:

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

PlayerController:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Unity_RestApi_Custom.Contracts;

namespace Unity_RestApi_Custom.Controllers
{
    [Route("api/[controller]")]
    public class PlayersController : Controller
    {
        int counter = 0;
        private static List<Player> players;

        public PlayersController(ILogger<PlayersController> logger)
        {
            //_logger = logger;
            players = new List<Player>();

            players.Add(new Player(1, "Name 1 Text", 1));
            players.Add(new Player(2, "Name 2 Text", 2));
            players.Add(new Player(3, "Name 3 Text", 3));
            System.Diagnostics.Debug.WriteLine("Testing Constructor");
        }

        /*
        [HttpGet(Name = "Players")]
        public IEnumerable<Player> Get()
        {
            Player player = players.Single(p => p.Id == id);
            return Enumerable.Range(0, players.Count).Select(index => new Player
            {
                Id = players[index].Id ,
                FullName = players[index].FullName,
                Score = players[index].Score
            })
            .ToArray();;
            yield return player;
        }*/

        [HttpGet]
        public JsonResult Get()
        {
            System.Diagnostics.Debug.WriteLine("Players Count == " + players.Count);
            return Json(players);
            //return new JsonResult(Random.Shared.Next());
        }

        [HttpGet("{id}")]
        public JsonResult Get(int id)
        {
            Player player = players.Single(p => p.Id == id);
            return Json(player);
        }

        [HttpPost]
        public JsonResult Post([FromBody] Player newPlayer)
        {
            players.Add(newPlayer);
            return Json(players);
        }

        [HttpPut("{id}")]
        public JsonResult Put(int id,[FromBody] int newScore)
        {
            /*Player player = players.Single(player => player.Id == id);
            player.Score = newScore;
            return Json(player);*/

            for (int i = 0; i < players.Count; i++)
            {
                if (players[i].Id == id)
                {
                    players[i].Score = newScore;
                }
            }

            return Json(players);
        }

        [HttpDelete("{id}")]
        public JsonResult Delete(int id)
        {
            List<Player> playersLocal = players;
            Player player = playersLocal.Single(player => player.Id == id);
            playersLocal.Remove(player);
            players = playersLocal;
            //System.Diagnostics.Debug.WriteLine("Players Count == "+ playersLocal.Count);
            return Json(players);
        }
    }
}

and Player model class:

using System;
using Newtonsoft.Json;

namespace Unity_RestApi_Custom.Contracts
{
    [JsonObject,Serializable]
    public class Player
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public int Score { get; set; }

        public Player(int Id,string FullName,int Score)
        {
            this.Id = Id;
            this.FullName = FullName;
            this.Score= Score;
        }
    }
}

Basically I am a newbie to Web API development therefore I don't know which direction to go.

4
  • What exact is the default state and where is the controller object reinitialized at which point in your code? Commented May 21, 2023 at 20:59
  • i think its builder.Services.AddControllers(); Commented May 21, 2023 at 21:24
  • Sorry but the question is not clear. What exactly is reinitializing? Commented May 21, 2023 at 21:28
  • The object has reinitialized because of your constructor as you are creating new list inside your constructor so whenever, the controller will be invoked your object will always be recreated. Commented May 23, 2023 at 1:12

1 Answer 1

0

The reason you have this issue is that you are creating the players list in the constructor of your controller.

The controller is a scoped resource, they are created and destroyed for every request, so each time, the constructor is called and it destroys the state of your static list.

To fix this, move the creation of your player list into an inline instatiator, or the static constructor of the controller (nb. using the static constructor is no guarantee, but it is closer to your intent)

        int counter = 0;
        private static List<Player> players = new List<Player>(new[] {
            new Player(1, "Name 1 Text", 1),
            new Player(2, "Name 2 Text", 2),
            new Player(3, "Name 3 Text", 3)
        };

        public PlayersController(ILogger<PlayersController> logger)
        {
            //_logger = logger;
            System.Diagnostics.Debug.WriteLine("Testing Constructor");
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.