简体   繁体   中英

Static objects for Web API 2

i have a web api 2 project the client will request some data that is in a xml format. That XML will never change and i am wondering how i could keep it in ram so that it doesnt deserialize the xml each time it needs data from that file.

Would deserializing it at launch and then keep it in a static variable be the best way as it will only be use for reading ?

 [HttpPost]
 [Route("api/dosomething")]
 public string DoSomething() {

     var myData = XmlSerializer(MyDataStruct).Deserialize(something);
     return myDate;
 }

Here the xml is only used to communicate values to clients. How can i make it so that i could deserialize it once and then return that directly. Would using static member enable this feature ?

A simple cache-aside approach with a static field could be a fair option:

private static MyDataStruct _myData;

[HttpPost]
[Route("api/dosomething")]
public string DoSomething() {
    if(_myData == null)
    {
        _myData = new XmlSerializer(typeof(MyDataStruct)).Deserialize(something);
    }

    return _myData;
}

If you want even better performance and completely skip both the deserialization from your XML and the serialization of your response body into JSON/XML, then I strongly suggest you an HTTP output caching approach, using a library like this one: AspNetWebApi-OutputCache .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM