Generic DAL using WCF: Part 6

In this article I would just give a tip on how to improve on the Generic DAL which we just finished in this series.
 
Though the Generic DAL which we had designed worked well. We still were not able to create a 100% Generic Solution in the previous article.
 
In order to achieve a 100% Generic Method , We need to take the Help of Reflection . We will need to call the method CreateObjectSet using Reflection.
 
This is how the Service Layer needs to be modified.
  1. using Microsoft.VisualBasic;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Collections.Generic;  
  5. using System.Data;  
  6. using System.Diagnostics;  
  7. using GenericDAL;  
  8. using System.Data.Objects;  
  9. using System.Reflection;  
  10.   
  11. // NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.  
  12. public class Service1 : IService1  
  13. {  
  14.        public TEntity Get(TEntity entity)  
  15.        {  
  16.               IEnumerable<TEntity> x1 = GetObjectSet(entity);  
  17.               return x1.First();  
  18.        }  
  19.        public object GetObjectSet(TEntity entity)  
  20.        {  
  21.               MCSEntities context = new MCSEntities();  
  22.               Type[] typeArgs = { ObjectContext.GetObjectType(entity.GetType()) };  
  23.               Type typObjectContext = context.GetType();  
  24.               Type[] NoParams = {  
  25.               };  
  26.               MethodInfo meth = typObjectContext.GetMethod("CreateObjectSet", NoParams);  
  27.               MethodInfo methGeneric = meth.MakeGenericMethod(typeArgs);  
  28.               return methGeneric.Invoke(context, null);  
  29.        }  
  30. }  
As can be seen in the above Service Class , the Get(TEntity entity) method makes use of the method GetObjectSet to get the ObjectSet.
 
The ObjectSet is created based on the Entity Object that is passed on the Client Side.
 
I have placed this code in a separate method as we will call it in all our methods. This method uses Reflection to call the Generic Method CreateObjectSet<TEntity>( ).
 
Hence using Reflection we are able to achieve 100% Generics.


Similar Articles