Monday 28 December 2015

How is the service instance created? How can you manage or control WCF service instance creation?


Service Instance

Client request can be served by using single service instance for all users, one service instance for one client, or one instance for one client request. You can control this behavior by using the technique called Instance Management in WCF.

There are three instance modes supported by WCF:


  • Per-Call: Service instance is created for each client request. This Service instance is disposed after response is sent back to client.
  • Per-Session (default): Service instance is created for each client. Same instance is used to serve all the requests from that client for a session. When a client creates a proxy to particular service, a service instance is created at server for that client only. When session starts, context is created and when it closes, context is terminated. This dedicated service instance will be used to serve all requests from that client for a session. This service instance is disposed when the session ends.
  • Singleton: All client requests are served by the same single instance. When the service is hosted, it creates a service instance. This service instance is disposed when host shuts down.



You can configure instance mode using [ServiceBehavior] attribute as below:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]

public class MyService:IGreetingService



In this post I explained what are the Instance mode of supported by WCF. I hope you enjoyed this post please comments your feed back and quires. Thank You.

Fault Contract - Handling Errors in WCF service

What is FaultContract?


How do you handle errors in ASP.NET? It's very simple - just by adding the simple Try & Catch blocks. But when you come to WCF Service, if any unexpected error occurred (like SQL server down/Unavailability of data/Divide By Zero) in service, then error/Exception details can be passed to Client by using Fault Contract.

False Assumption

Most people think that we can't throw FaultException in catch block. It should be only based on some condition (if condition). But it is a false assumption. The main objective is, any type of exceptions(Predicted or Unpredicted) from service to be passed to Client (WCF Service consumer).

Using code:-



    [DataContract()]
    public class CustomError
    {
        [DataMember()]
        public string ErrorCode;
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ErrorDetail;
    }

    [ServiceContract()]
    public interface IGreetingService
    {
        [OperationContract()]
        [FaultContract(typeof(CustomError))]
        string Greet(string userName);
    }

    public class GreetingService : IGreetingService
    {
        public string Greet(string userName)
        {
            // predicted Errors
            if (string.IsNullOrWhiteSpace(userName))
            {
                var exception = new CustomError()
                {
                    ErrorCode = "401",
                    Title = "Null or empty",
                    ErrorDetail = "Null or empty user name has been                                          provided"
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                       Input error");
            }


            // Unpredictable Errors...
            try
            {
              SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                // some database operation code..
                con.Close();

            }
            catch (SqlException sqlEx)
            {
               var exception = new CustomError()
               {
                   ErrorCode = "402",
                   Title = "Null or empty",
                   ErrorDetail = "Connection can not open this " +
                                 "time either connection string is wrong                                     or Sever is down. Try later"
               };
               throw new FaultException<CustomError>(exception, "Reason :                                                       Server down");
            }
            catch (Exception ex)
            {
                var exception = new CustomError()
                {
                    ErrorCode = "403",
                    Title = "Null or empty",
                    ErrorDetail = "unforeseen error occurred. Please try                                      later."
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                        Unforeseen Error");
              
            }


           // If there is no Error...
            return string.Format("Welcome {0}", userName);
        }
    }




In this post I explained how to handle exception at service side in WCF. I hope you enjoyed this post please comments your feed back and quires. Thank You.