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.

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using GenericDAL;
using System.Data.Objects;
using System.Reflection;

// NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
      
 
       public TEntity Get(TEntity entity)
       {
              IEnumerable<TEntity> x1 = GetObjectSet(entity);
              return x1.First();
       }
 
       public object GetObjectSet(TEntity entity)
       {
              MCSEntities context = new MCSEntities();

              Type[] typeArgs = { ObjectContext.GetObjectType(entity.GetType()) };
              Type typObjectContext = context.GetType();
              Type[] NoParams = {

              };
              MethodInfo meth = typObjectContext.GetMethod("CreateObjectSet", NoParams);
              MethodInfo methGeneric = meth.MakeGenericMethod(typeArgs);

              return methGeneric.Invoke(context, null);
       }

}

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 .

Up Next
    Ebook Download
    View all
    Learn
    View all