HelloWorld1010 HelloWorld1010 - 2 months ago 17
ASP.NET (C#) Question

Dependency injection for ApiController?

Im working on a sample project where I need to create a GET method that saves the results in memory and not into a database.

Originally I created the dictionary in PersonController; however, that is a problem since it doesn't persist in memory after the GET request. I need to figure out how to only create one instance of NumbersByName and pass it into the Api Controller. Can this be done?

public class PersonController : ApiController
{
private readonly Dictionary<string, List<int>> NumbersByName;

public PersonController(Dictionary<string, List<int>> numbersByName)
{
NumbersByName = numbersByName;
}

[HttpGet]
public IHttpActionResult GetPersonsNumbers(string name)
{
var personsNumbers = NumbersByName[name];

return Ok(personsNumbers);
}
}

Answer

Well you can use cache to store the data

Example:

public string[] GetNames()
{
  string[] names = null;
  if(Cache["names"] == null)
  {
    names = DB.GetNames();
    Cache["names"] = names;
  }
  else
  {
    names = Cache["names"];
  }
  return names;
}

You can apply the same concept in your code. You can take a look at This

Otherwise, you need to investigate using the singleton design pattern, that way you only create one instance.