Ninject 注入到通过反射构造的对象中
我们遇到了一个问题,我们希望将依赖项注入到通过反射构造的对象中:
Type _type = Type.GetType(className, true, true);
ConstructorInfo _ctor = _type.GetConstructor(new[] { typeof(MyClass) });
IReg _reg = (IReg)_ctor.Invoke(new object[] { _myClass });
这里似乎没有使用属性注入进行注入。难道不可能吗?我们如何解决这个问题? 谢谢。
We have hit an issue where we would like to inject a dependency into an object that has been constructed via reflection:
Type _type = Type.GetType(className, true, true);
ConstructorInfo _ctor = _type.GetConstructor(new[] { typeof(MyClass) });
IReg _reg = (IReg)_ctor.Invoke(new object[] { _myClass });
The injection does not seem to be happening here using property injection. Is it not possible? How can we get around this issue?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在对象构造后使用 IKernel 上的
kernel.Inject(Object)
方法通过反射对其进行属性注入。但这将是构造后,您将不会得到任何构造函数注入。You can do property inject on the object after it's construction via reflection with the
kernel.Inject(Object)
method on IKernel. But this WILL be post construction and you will not get any constructor injection.有一个
Kernel.Get(Type)
,但是当您想调用特定的构造函数时,它没有用。有一个可自定义的构造函数选择策略,您可以使用它来模拟您在第二行中所做的事情。There's a
Kernel.Get(Type)
, but as you want to call a specific constructor, it's no use. There is a constructor selection strategy which is customizable, which you could use to emulate what you're doing in your second line.要使用依赖注入框架,您不应该使用 new 或反射来实例化对象本身,您应该调用注入框架。
在您的情况下:
基于先前的配置(使用 Ninject 的 Bind 调用),使用依赖项注入框架来避免使用反射进行对象实例化 + 连接其依赖项。
To use the dependency injection framework you shouldn't instantiate object by itself using new or reflection you should call the injection framework.
In your case:
Any way the dependency injection framework is used to avoid using reflection for object instantiation + wiring it's dependencies, based on previously configuration (using Bind calls for Ninject).