How to implement caching in WCF?



Hi
Here we can’t implement the caching like Web service. We can implement caching with help of HttpContext.

I hope that you are knowing basic concept of WCF. so i m skipping that steps.

Step1:Declare 2 methods in Interface like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

[ServiceContract]
public interface IService
{
[OperationContract]

string DisplayDate();

[OperationContract]

string DisplayDate_WithOutCache();

}

step2:Write WCF 2 methods like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;

public class Service : IService
{

public string DisplayDate()
{

HttpContext context = HttpContext.Current;

if (context.Cache[“str”] != null)
{
return (string)context.Cache[“str”];
}
else
{
string str = System.DateTime.Now.ToString();
context.Cache.Insert(“str”, str, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);
return str;
}

}

public string DisplayDate_WithOutCache()
{
string str1 = System.DateTime.Now.ToString();
return str1;
}
}

Step3: Compile the service and consume in application

Step4: Write this code in Button Click event to test the concept

protected void Button1_Click(object sender, EventArgs e)
{
Service client = new Service();
LblMsg.Text = client.DisplayDate();
lblmsg1.Text = client.DisplayDate_WithOutCache();
}

Step5: Now compile the application.

Advertisement

2 thoughts on “How to implement caching in WCF?

  1. javascript forum August 7, 2012 / 6:33 pm

    Attractive section of content. I just stumbled upon your blog and in accession capital to assert
    that I get in fact enjoyed account your blog posts.

    Anyway I will be subscribing to your augment and even I achievement you access consistently fast.

  2. Belinda June 17, 2014 / 3:06 pm

    This is a topic that’s close to my heart… Many
    thanks! Exactly where are your contact details though?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.