Ninject注入通过反射构造的对象

时间:2011-08-16 22:05:31

标签: reflection ninject

我们遇到了一个问题,我们希望将依赖注入到通过反射构建的对象中:

        Type _type = Type.GetType(className, true, true);
        ConstructorInfo _ctor = _type.GetConstructor(new[] { typeof(MyClass) });
        IReg _reg = (IReg)_ctor.Invoke(new object[] { _myClass });

使用属性注入似乎没有发生注射。这不可能吗?我们如何解决这个问题? 感谢。

3 个答案:

答案 0 :(得分:1)

你可以通过在IKernel上使用kernel.Inject(Object)方法进行反射,在构造对象后对属性进行属性注入。但这将是后期构建,你不会得到任何构造函数注入。

答案 1 :(得分:0)

要使用依赖注入框架,您不应该使用new或反射来实例化对象,您应该调用注入框架。 在你的情况下:

//setup the application
IKernel kernel = new StandardKernel();
//add all your other bindings for property injection
...

kernel.Bind<MyClass>.ToConstant(_myClass); //if same _myClass instance is used than this can go in setup application. 
Type _type = Type.GetType(className, true, true);
var _reg = kernel.Get(_type);
kernel.Unbind<MyClass>(); //cleanup the global kernel

使用依赖注入框架的任何方式都可以避免使用反射进行对象实例化,并根据以前的配置(使用 Bind 调用Ninject)来连接它的依赖项。

答案 2 :(得分:0)

有一个Kernel.Get(Type),但是你想调用一个特定的构造函数,它是没用的。有一个可自定义的构造函数选择策略,您可以使用它来模拟您在第二行中所执行的操作。