Thursday, 20 March 2014

How does caching work on WCF services?

Caching in WCF Services

Suppose, user sends request to a service so at server, than service method is called and it response and sent result back to user. But, if we configure caching at service, then service method won’t called, cached response is sent back. If cache expired, then next time service method is called and the response will again cache.

How caching is implemented in WCF services?

1.      Mandatory Configuration: In service Side enable ASP.NET compatibility mode in the Web.config file.
<system.serviceModel>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
 </system.serviceModel>


2.       Attach a Cache Profile: Cache Profile settings are maintained in web.config under system.web settings
<outputCacheSettings>
 <outputCacheProfiles>
  <add name = ""
enabled = "true"
 duration = "-1"
location = ""
sqlDependency = ""
varyByCustom = ""
varyByControl = ""
varyByHeader = ""
varyByParam = ""
noStore = "false"/>
</outputCacheProfiles>
</outputCacheSettings>
  • Attributes of the cache profile are: Duration and varyByParam
  • Duration: Time duration for which the response is cached.
  • varyByParam: Separate cached responses for different query parameters.
3)  AspNetCacheProfile attribute  Enable AspNetCompatibilityRequirementsAttribute and set RequirementsMode to Allowed or Required. The default value is NotAllowed. This attribute is required to the service so that service can run in ASP.NET compatibility code. Next, Apply AspNetCacheProfileAttribute to a service operation. This attribute specifies a cache profile name. In our case, Cache profile name is “CustomCache” which we declared in web.config earlier.
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
         [AspNetCacheProfile("CustomCache")]
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
      
    }

No comments:

Post a Comment