【问题标题】:Activator.CreateInstance and Ninject on asp.net mvc 4asp.net mvc 4 上的 Activator.CreateInstance 和 Ninject
【发布时间】:2015-12-14 05:38:57
【问题描述】:

我正在尝试在同一个项目中使用反射和 ninject。这是我的代码:

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

这是我的包含该方法的类:

 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 "";
        }
    }

我收到一条错误消息,提示找不到构造函数。解决方案是添加一个空的默认构造函数,但这不会注入我想要的类。有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: asp.net-mvc-4 ninject.web.mvc .net-reflector


    【解决方案1】:

    您将需要一个IEventService 的具体实例作为参数传递给DataClassctor,例如Activator.CreateInstance(type, instance);,因此您有很多方法可以做到这一点,请参阅以下 2:

    1st - 类有一个具体的 IEventService

    您进行反射的那个类有一个IEventService 的具体实例,然后您只需将 param 传递给 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 - 获取 Ninject 的 IKernel 实现

    如果您使用的是NinjectWebCommom,您只需将 bootstrapper 属性更改为 public 并获得这样的内核 NinjectWebCommom.bootstrapper.Kernel.get&lt;IEventService&gt;()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多