How to write a generic service in WCF
Posted
by rezaxp
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by rezaxp
Published on Wed, 30 May 2012 21:01:00 GMT
Indexed on
2012/05/30
22:41 UTC
Read the original article
Hit count: 461
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.
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);
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" />
© ASP.net Weblogs or respective owner