How to write a generic service in WCF
In one of my recent projects I needed a generic service as a facade to handle General activities such as CRUD.Therefor I searched as Many as I could but there was no Idea on generic services so I tried to figure it out by my self.
( I'm using a self hoster and this article's target is the people who know about WCF and it's concepts so you can find more about WCF here : http://msdn.microsoft.com/en-us/netframework/aa663324.aspx)
Finally,I found a way :
Create a generic contract as below :
[ServiceContract]
public interface IEntityReadService<TEntity> where TEntity : EntityBase, new() { [OperationContract(Name = "Get")] TEntity Get(Int64 Id); [OperationContract(Name = "GetAll")] List<TEntity> GetAll(); [OperationContract(Name = "GetAllPaged")] List<TEntity> GetAll(int pageSize, int currentPageIndex, ref int totalRecords);
[OperationContract(Name = "GetAllConditional")] List<TEntity> GetAll(string whereClause, string orderBy, int pageSize, int currentPageIndex, ref int totalRecords); }
then create your service class :
public class GenericService<TEntity> :IEntityReadService<TEntity>where TEntity : EntityBase, new(){#region Implementation of IEntityReadService<TEntity> public TEntity Get(long Id) { return BusinessController.Get(Id); } public List<TEntity> GetAll() { try { return BusinessController.GetAll().ToList(); } catch (Exception ex) { throw; } } public List<TEntity> GetAll(int pageSize, int currentPageIndex, ref int totalRecords) { return BusinessController.GetAll(pageSize, currentPageIndex, ref totalRecords).ToList(); } public List<TEntity> GetAll(string whereClause, string orderBy, int pageSize, int currentPageIndex, ref int totalRecords) { return BusinessController.GetAll(pageSize, currentPageIndex, ref totalRecords, whereClause, orderBy).ToList(); }#endregion
}Then, set your EndPoint configuration in this way :<endpoint address="myAddress" binding="basicHttpBinding" bindingConfiguration="myBindingConfiguration1" contract="Contracts.IEntityReadService`1[[Entities.mySampleEntity, Entities]], Service.Contracts" />