Search code examples
c#apiservicecontrollerpersist

C# Web API service data not persisting


I currently have a C# web API and the api controller has a STATIC service so if a call is made to add data the data will be able to be referenced later on. I don't want this variable to be static, but every time i make an API call the service, which contains a List of data, is reset if it isn't static. How can I work around this?


Solution

  • A Webapi controller is created on each request (see ASP.net Web API: Why are controllers created per request?) so this means that any variables that are instantiated within the webapi controller constructor will be recreated on each request. A static service will still retain its value between requests because its lifetime is not controlled by the webapi controller.

    To have a non-static service, you will have to introduce another way to control the lifetime of the service. Look at dependency injection http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection to get a better idea of how to do this. The easiest way to get around your issue is to use an IoC container such as http://www.ninject.org/.