Click here to Skip to main content
15,039,470 members
Articles / Programming Languages / C#
Posted 18 May 2010

Tagged as


40 bookmarked

How to abstract a WCF Service out of business logic

Rate me:
Please Sign up or sign in to vote.
4.47/5 (11 votes)
18 May 2010CPOL3 min read
Service Bus Architecture based on WCF (2): Abstract WCF.


People always discuss how to abstract a WCF Service out of the business logic? How could we make minimize changes to expand our existing system to a WCF Service? Put it in another way, we always wish we could develop our applications without worrying about those services we could possibly need to open in the future. When we really need those services, we simply load a service component and make a very small refactoring to make it work. My design here is to encapsulate the subscription and the abstracted function service into a Service Engine. And on the client side, I design an endpoint to communicate with the Service Engine.



I abstract the service out of the business logic based on the last part: how to subscribe to WCF.

Using the code

Service Engine

In my last article, in order to open all the functions to the client, I added NewInventory, UpateInventory, and so on into InventoryService. This will prevent us from abstracting the service out of the business. What I'm going to do is write a single method named Invoke to provide the service to all the client calls.

public class SAOTService<T> : ISAOTService
    public object Inovke(string methodname, params object[] args)
            object obj = typeof(T).InvokeMember(methodname, BindingFlags.Static |
                BindingFlags.Public | BindingFlags.IgnoreCase | 
                BindingFlags.InvokeMethod, null, null, args);
            return obj;
        catch (Exception ex)
            return ex.Message;

In order to completely abstract the service out of the business logic. I designed a generic <T> in the service implementation class. <T> will accept a class type providing the real static functions. On the server application, if you want to open some of your functions to the WCF Service, create an adapter class:

public class ServiceAdapter
    public static Inventory GetInventory(int productid)
        return Inventory.GetInventory(productid);
    public static Inventory[] GetInventoryList()
        return Inventory.GetInventoryList();
    public static bool ChangeInventory(string user, int productid, int changednumber)
        Inventory inv = Inventory.GetInventory(productid);
        return inv.ChangeInventory(user, changednumber);
    public static int CreateNewProduct(Inventory inventory, string user)
        return new Inventory(user,inventory.ProductName,inventory.CurrentInventory).ProductID;

Then, when you refer to the Service Engine, send the adapter into the abstracted service.


On the client side, open the connection to the service:


After that, you use the Invoke method the get the ServiceAdapter functions.

FunctionServiceConnector.GetService("Inventory").Invoke("GetInventory", 1)
//get product inventory with id=1

For the subscription part, in order to avoid the known type issue, I design the subscription message to be a fixed class Message:

public class Message: EventArgs
    #region Properties
    public string Title { get; set; }
    public string Content { get; set; }
    public string Context { get; set; }
    public DateTime Createtime { get; set; }
    public string PrimaryID { get; set; }
    public string Sender { get; set; }
    public string To { get; set; }
    public string CC { get; set; }
    public DateTime ExpiredTime { get; set; }
    public string Attachment { get; set; }
    public string FunctionCode { get; set; }
    public string ServiceName { get; set; }

Content and Context will store complicated information needed to be sent. There are two standard methods in IMessageSenderCallBack to provide all the subscription information to the clients: void SendMessage(Message message); void SendHeartBeat(string address);

[ServiceContract(SessionMode = SessionMode.Required, 
        CallbackContract = typeof(IMessageSenderCallBack))]
public interface IMessageSender
  [OperationContract(IsOneWay = false, IsInitiating = true, 
   IsTerminating = false)]
  void Init(string address);
public interface IMessageSenderCallBack
  [OperationContract(IsOneWay = true)]
  void SendMessage(Message message);
  [OperationContract(IsOneWay = true)]
  void SendHeartBeat(string address);

SendHeartBeat keeps sending a heart beat information to the client to indicate the server is still running. SendMessage encapsulates a message to the client to indicate the client to do the next logic in terms of the message.

The finished Service Engine has two important methods that will be invoked by the host application:

ServiceController.OpenFunctionService<T>(in portnumber,string servicename);
ServiceController.OpenMessageService(in portnumber, string servicename);

Note: If you debug the function, you will encounter an exception that Inventory is unknown in SAOTService. Since we didn't put the Inventory into SAOTService, the service is not able to recognize this class and serialize it properly. In order to let the serializer know this type, we add the KnownType attribute on the service interface.

[ServiceKnownType("GetKnownTypes", typeof(KnowTypes))]

This statement tells the serializer that the static method GetKnownTypes in the class KnowTypes will provide a type list to let the serializer recognize all the types in the list.

public static class KnowTypes
    private static List<type> MyKnownTypes = new List<type>();
    public static void AddKnownType(Type type)
    public static IEnumerable<type> GetKnownTypes(ICustomAttributeProvider provider)
        return MyKnownTypes.ToArray();

Then, before we open the service, add these statements:


Remember, the same exception will happen in the client code as well.


Service EndPoint

I create two classes to receive the function service and the subscription service from the Service EndPoint.

//get subscription service
class MessageDistributor : Trilobita.SAOT.Object.IMessageSenderCallBack

In MessageDistributor, four events will tell the client application that subscription messages are coming:

//a subscription message arrives
public event EventHandler<Message> MessageDelivered;
// server connected
public event EventHandler
// server disconnected
public event EventHandler
// heart beat message from server every 2 seconds
public event EventHandler HeartBeatFromServer;

Open and close Subscription Service:

//open the subscription connection between client and server
// close the subscription connection between client and server

Open and close Function Service:

FunctionServiceConnector.CreateFunctionService<T>(servicename, address);

// get a function service proxy
FunctionServiceConnector.GetFunctionService<T>( servicename));


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

China China
No Biography provided

Comments and Discussions

GeneralMy vote of 5 Pin
gbarizon11-Jul-12 9:02
Membergbarizon11-Jul-12 9:02 
GeneralRe: My vote of 5 Pin
WillCaptain15-Jan-13 3:42
MemberWillCaptain15-Jan-13 3:42 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey16-Apr-12 3:19
professionalManoj Kumar Choubey16-Apr-12 3:19 
QuestionProcess Manager Pin
wassmuss24-Jun-11 2:59
Memberwassmuss24-Jun-11 2:59 
AnswerRe: Process Manager Pin
WillCaptain26-Jun-11 21:12
MemberWillCaptain26-Jun-11 21:12 
GeneralMy vote of 5 Pin
IvanKhan5-Mar-11 6:23
professionalIvanKhan5-Mar-11 6:23 
GeneralIn Agrrement Pin
aSarafian19-May-10 3:28
MemberaSarafian19-May-10 3:28 
Personally I agree with you thoughts.

On a disconnected application, the communication layer is relatively difficult. So it shouldn't be open to exposure to any process that requires creating new functionality or updating one.

For the reason when we first migrated to WCF, I created one interface that handles messages. The hole implementation was located in a framework, and each message could be redirected on the server to the appropriate execution thought a config file.
Having this mechanism allowed us to write typed messaged (I created a tool to generate the code) and its relatice execution without even knowing details about the communication layer.
GeneralRe: In Agrrement Pin
WillCaptain19-May-10 3:58
MemberWillCaptain19-May-10 3:58 
GeneralRe: In Agrrement Pin
aSarafian19-May-10 5:05
MemberaSarafian19-May-10 5:05 
GeneralRe: In Agrrement Pin
WillCaptain19-May-10 5:13
MemberWillCaptain19-May-10 5:13 
GeneralRe: In Agrrement Pin
aSarafian19-May-10 5:21
MemberaSarafian19-May-10 5:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.