asp.net-mvc-4ninject.web.mvc.net-reflector

Activator.CreateInstance and Ninject on asp.net mvc 4


I am trying to use reflection and ninject on the same project. Here is my code :

Type type = Type.GetType("MySolution.Project.Web.App_Code.DataClass");
MethodInfo theMethod = type.GetMethod("Events_ListAll");
object classInstance = Activator.CreateInstance(type, null);

And here is my class that contains that method:

 public class DataClass
    {
        private IEventService eventService;
        public DataClass(IEventService eventService)
        {
            this.eventService = eventService;
        }


        public String Events_ListAll()
        {
            List<Event> lstEvents = eventService.GetEvents().ToList<Event>();
            return "";
        }
    }

I get an error saying that there is no constructor found. The solution to that would be to ad an empty default constructor, but that wont inject class I want. Is there any workaround to solve this?


Solution

  • You will need a concrete instance of IEventService to pass as parameter to ctor of DataClass, like this Activator.CreateInstance(type, instance);, so you got many approaches to do that, see 2 of :

    1st - class has a concrete IEventService

    That class where you doing the reflection has a concrete instance of IEventService and then you just pass as param to the Activator:

    public class Foo
    {
       public Foo(IEventService eventService)
       {
           Type type = Type.GetType("MySolution.Project.Web.App_Code.DataClass");
           MethodInfo theMethod = type.GetMethod("Events_ListAll");
           object classInstance = Activator.CreateInstance(type, eventService);
       }
    }
    

    2nd - Get IKernel implementation of Ninject

    If you are using NinjectWebCommom you can just change the bootstrapper prop to public and get the kernel like this NinjectWebCommom.bootstrapper.Kernel.get<IEventService>()

    Type type = Type.GetType("MySolution.Project.Web.App_Code.DataClass");
    MethodInfo theMethod = type.GetMethod("Events_ListAll");
    object classInstance = Activator.CreateInstance(type, Kernel.Get<IEventService>());