Shared Service Contracts and Data Contracts in WCF

This article describes you how to create WCF ServiceContracts and DataContracts that can be shared to multiple assemblies or wcf services and clients.

In many scenarios sharing of WCF contracts is useful like if you multiple WCF service assemblies that shared service contracts and data contracts or if you want to create a wrapper that would instantiate service proxies or you want to have dynamic creation of service proxies using ChannelFactory to avoid ServiceContract changes issues.


We will follow below steps to create Service Contracts and Data Contracts that can be shared in multiple assemblies.


Create New blank solution

Open your visual studio and from file menu select New -> Project -> Other Project Types -> Visual Studio Solutions -> Blank Solution name solution as NorthwindDynamicProxy and click Ok.

Create below projects under NorthwindDynamicProxy solution.

NorthwindContracts: right click on NorthwindDynamicProxy solution select Add -> New Project -> Visual C# -> Class Library name it as NorthwindContracts and click Ok. The NorthwindContracts class library will create required WCF Service Contracts and DataContracts which can be shared to multiple WCF Services and clients.

Add Reference to below namespace

                
System.ServiceModel
System.Runtime.Serilization
                    
            

NorthwindServices: right click on NorthwindDynamicProxy solution select Add -> New Project -> Visual C# -> WCF -> WCF Service Library name it as NorthwindServices and click Ok. This NorthwindServices WCF service library will use ServiceContracts and DataContracts created by NorthwindContracts assembly.

NorthwindDynamicProxy Solution will look like below image.

WCF Dynamic Proxy


Shared WCF DataContract

This step creates Northwinid DataContract that can be shared among multiple assemblies.

As shown in previous image create folder DataContracts under NorthwindContracts project.

Add Category: under DataContract folder. Category DataContract will be used in Category ServiceContract. Add below DataMembers to Category DataContract

                
using System.Runtime.Serialization;  
using System.ServiceModel; 

namespace NorthwindContracts.DataContracts
{
    [DataContract] 
    public class Category
    {
        [DataMember] 
        public int CategoryID { get; set; }

        [DataMember] 
        public string CategoryName { get; set; }

        [DataMember] 
        public string CategoryDescription { get; set; }
    }
}
           

Shared WCF ServiceContract

Create new folder ServiceContracts under NorthwindContracts project. This folder will have Category and Product ServiceContract

Category Service Contract: Add interface to ServiceContracts folder name it as ICategoryService. Add below OperationContract to ICategoryService.

                
using System.ServiceModel;
using NorthwindContracts.DataContracts; 

namespace NorthwindContracts.ServiceContracts
{
    [ServiceContract(Name = "CategoryService",
            Namespace = "http://northwind.com/categoryservice")]
    public interface ICategoryService
    {
        [OperationContract]
        string GetCategoryName(int categoryID);

        [OperationContract]
        Category GetCategoryDetails(int categoryID);
    }
}        
            

Product Service Contract: Add interface to ServiceContracts folder name it as IProductService. Add below OperationContract for IProductService.

                
using System.ServiceModel;  

namespace NorthwindContracts.ServiceContracts
{
    [ServiceContract(Name = "ProductService", 
        Namespace = "http://northwind.com/productservice" )]
    public interface IProductService
    {
        [OperationContract] 
        string GetProductName(int productID);

        [OperationContract]
        int GetProductQty(int productID);
    }
}       
    

Implement shared WCF contracts

Open NorthwindServices project from Solution Explorer and create three folders with name of CategoryServices, ProductServices and ServiceHosts.

Add reference of NorthwindContracts assembly to NorthwindServices service library.

Add new class file with name CategoryService under CategoryServices folder. CategoryService implements ICategoryService service contract from NorthwindContracts assembly. Below is implementation of each OperationContract from ICategoryService service contract.

                
using NorthwindContracts.DataContracts;
using NorthwindContracts.ServiceContracts;
using System.ServiceModel;  
    
namespace NorthwindServices.CategoryServices
{
    [ServiceBehavior(Name = "CategoryService",
            Namespace = "http://northwind.com/categoryservice")] 
    public class CategoryService : ICategoryService 
    {
        public string GetCategoryName(int categoryID)
        {
            return "Beverages";
        }

        public Category GetCategoryDetails(int categoryID)
        {
            Category category = new Category();
            category.CategoryID = 1;
            category.CategoryName = "Beverages";
            category.CategoryDescription
                        = "Soft drinks, coffees, teas, beers, and ales";

            return category;
        }
    }
}
            

Add new class file with name ProductService under ProductServices folder. ProductService implements IProductService service contract from NorthwindContracts assembly. Below is implementation of each OperationContract from IProductService service contract.

                
using System.ServiceModel;
using NorthwindContracts.ServiceContracts; 

namespace NorthwindServices.ProductServices
{
    [ServiceBehavior(Name = "ProductService",
            Namespace = "http://northwind.com/productservice")] 
    public  class ProductService : IProductService 
    {
        public string GetProductName(int productID)
        {
            return "Aniseed Syrup";
        }

        public int GetProductQty(int productID)
        {
            return 13;
        }
    }
}
            

Create Service Hosts

CategoryServiceHost.svc: Create new WCF Service file with name as CategoryServiceHost.svc under ServiceHosts folder created in previous step. Add below ServiceHost attribute details to this file.

                
<%@ ServiceHost 
    Service="NorthwindServices.CategoryServices.CategoryService" %>
                    
            

ProductServiceHost.svc: Create new WCF Service file with name as ProductServiceHost.svc under ServiceHosts folder created in previous step. Add below ServiceHost attribute details to this file.

                
<%@ ServiceHost 
        Service="NorthwindServices.ProductServices.ProductService" %>
            

Create Service Endpoint

In this step we will create service endpoint for Category and Product services in App.config of NorthwindServices Service Library. Contracts of those endpoints are from NorthwindContracts assembly which is different than its own assembly. Open App.config file and add below endpoint details.

                
<system.serviceModel>
<services>
<service name="NorthwindServices.ProductServices.ProductService">
<host>
    <baseAddresses>
    <add baseAddress = 
        "http://localhost:7741/NorthwindServices
                /ProductServices/ProductService" />
    </baseAddresses>
</host>
        
<endpoint address = "" binding="wsHttpBinding" 
        contract="NorthwindContracts.ServiceContracts.IProductService"
        bindingNamespace ="http://northwind.com/productservice" >               
</endpoint>        

<endpoint address="mex" binding="mexHttpBinding"
            contract="IMetadataExchange" />
</service>

<service name="NorthwindServices.CategoryServices.CategoryService">
<host>
    <baseAddresses>
    <add baseAddress = 
            "http://localhost:7741/NorthwindServices
                    /CategoryServices/CategoryService" />
    </baseAddresses>
</host>
<endpoint address = "" binding="wsHttpBinding" 
            contract="NorthwindContracts.ServiceContracts
                        .ICategoryService"
            bindingNamespace ="http://northwind.com/categoryservice" >
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
        contract="IMetadataExchange" />
</service>
</services>

<behaviors>
<serviceBehaviors>
<behavior>          
    <serviceMetadata httpGetEnabled="True"/>          
    <serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>
                    
            

Host WCF Service Library

You can execute NorthwindServices WCF Service Library by pressing F5 and test services using WCFTestClient.

NorthwindServices WCF Service Library is ready to host with shared contracts. You can have hosting wcf service in IIS or hosting wcf services in windows services.

Open IIS manager and click on website which you created for this WCF Service Library. Right click on ProductServiceHost.svc and click on View in Browser.

Product Service


Create dynamic proxy using ChannelFactory

Use this shared contract library to create dynamic wcf proxy using ChannelFactory.

Download source code.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by Chinju at 8/27/2015 11:53:00 PM
Good explanations!!
post comment on dotnetmentors.com