mercredi 16 mars 2016

How to create reference of an interface class through Reflection in C#

I'm using repository structure in my application.

I have a interface class IDemoService

public interface IDemoService
    {
        bool CreateDemo(Demo demo);
        bool UpdateDemo(Demo demo);
        bool DeleteDemo(int id);
        Demo GetDemo(int id);
        Demo GetDemoServiceByName(string name);
        IEnumerable<Demo> GetAllDemo();
        void SaveRecord();
    }

with using System.Reflection; I need to create reference like

IDemoService iDemoService;

I've tried this way so far:

   var iDemoServiceClass = asm.GetTypes().Where(p =>
         p.Namespace == nameSpace &&
         p.Name == "IDemoService"
       ).ToList();
    Type iDemoServiceClassType = iDemoServiceClass.FirstOrDefault();
    var className = iDemoServiceClassType.Name;
    var functionName = "Get" + iDemoServiceClassType + "ByName";
    MethodInfo getMethod = demoServiceClassType.GetMethod(functionName);

    var instanceCreate = Activator.CreateInstance(iDemoServiceClassType);//, null); //here I want to create reference instead instance
    ParameterInfo[] parameters = getMethod.GetParameters();

    if (parameters.Length > 0)
    {
        object[] parametersArray = new object[] { "RequiredDemo" };
        var demoObj = getMethod.Invoke(instanceCreate, parametersArray);
    }

Since it is interface so can't create instance but reference is possible. So, is it possible anyway to create reference using Reflection or any other way? Please help me right way. Thanks advance :D





Aucun commentaire:

Enregistrer un commentaire