-1
\$\begingroup\$

I have a simple web api where each request "item" is stored in a list and thus a list is built without creating a new list per request. I have achieved this via dependency injection , but I want to know if there is a better way to do it?

[ApiController]
[Route("[controller]")]
public class MyController: ControllerBase
{
    private readonly List<string> _items;

    public WeatherForecastController(List<string> items)
    {
        _items = items;
    }

    [HttpPost]
    public ActionResult GetList([FromBody] CustomRequestObject request)
    {
        _items.Add(request.Item);

        return Ok(new CustomResponseObject(){Items = _items});
    }
}

public class CustomRequestObject
{
    public string Item { get; set; }
}

public class CustomResponseObject
{
    public IList<string> Items { get; set; }
}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSingleton<List<string>>(); //items stored after each request
    }

    //rest of startup methods left for simplicity
}
\$\endgroup\$
3
  • \$\begingroup\$ What is the expected lifetime of your data? \$\endgroup\$ – Peter Csala Apr 20 at 9:23
  • \$\begingroup\$ Are you not interested in retaining this data when the server reboots? How about after a period of not having received any web requests? \$\endgroup\$ – Flater Apr 20 at 14:09
  • \$\begingroup\$ Why not simply use a DB? \$\endgroup\$ – BCdotWEB Apr 20 at 14:29
0
\$\begingroup\$

It really depends, how far you want to go with this.

Maybe the most common suggestion that I can give is that what you are doing is called Memory Caching. It's good to call things with a name that is widely understood.

Read this article about In memory caching in Asp.net core.

Just to give you an example, what can be a possible issue with your code. Let's say you will have 2 instances of the same API, for scaling purposes. Guess what is going to happen? Every instance is going to work with its own in-memory list.

A side issue (not related to your question): you never except for function GetList to add something to the list. :)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.