使用 Activator.CreateInstance 时解析注入实例
我试图弄清楚如何让温莎城堡解决使用 Activator.CreateInstance 创建的对象的依赖关系。
目前,当我以这种方式创建对象时,创建的对象内部的依赖关系没有得到解决。我进行了搜索,看看是否有温莎方法可以做同样的事情,同时也解决依赖性,但到目前为止我还没有找到任何东西。
至于为什么我以这种方式创建实例,我正在玩一个基本的文本游戏来获得一点乐趣,并且实例是根据用户输入命令创建的,所以我需要根据字符串创建实例(目前,该命令在字典中映射到然后使用上述方法创建的类型)。
感谢您的任何和所有帮助。
I'm trying to figure out how to have Castle Windsor resolve dependancies for objects created using Activator.CreateInstance
.
Currently when I create objects this way, the dependancies inside the created object do not get resolved. I've had a search around to see if there's a Windsor method that does the same thing whilst also resolving the dependancies but I haven't found anything thus far.
As for why I'm creating instances this way, I'm playing about with a basic text game for a bit of fun and the instances are being created based on user input commands and so I need to create the instance based on a string (currently the command is mapped in a Dictionary to a type which is then created using the above method).
Thanks for any and all help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,您可以在温莎城堡注册,您可以注册所谓的“命名实例”,这样您就可以通过容器解析它们来创建您需要的对象,而无需处理肯定无法执行 IoC 的 Activator.CreateInstance 。
基本上,您必须使用 key: 注册您的组件
,然后调用以
正确创建您的组件并解决所有依赖项。
AFAIK you can register in castle windsor you can register the so called "named instances" so you can create the object you need by resolving them througth the container without dealing with Activator.CreateInstance that for sure can't perform IoC.
Basically you have to register your component with a key:
and then call
to have back your component properly created with all dependencies resoved.
为了扩展 Felice 给出的答案,我认为根据已接受的答案发布我得出的解决方案会很有用。
目前,我的命令通过
IDictionary
映射,但很快就会转移到其他介质(XML、JSON 等)。以下是我注册用户输入命令的组件
以及解析实例的方法:
To expand on the answer given by Felice I thought it'd be useful to post the solution I came to based on the accepted answer.
Currently my commands are mapped via an
IDictionary<TKey,TValue>
but will be moved to another medium soon (XML, JSON, etc).Here's how I'm registering the compnents for user input commands:
and to resolve the instance:
从温莎的角度来看,更好的实现是使用类型化工厂。使用类型化工厂,您的代码不必引用容器,因为会自动为您创建工厂实现。
使用类型化工厂,您的工厂可能如下所示:
Windsor 会将每个工厂方法转发到相应的解析 - 例如
GetMove
将变为container.Resolve("Move")< /代码>。
请参阅 类型化工厂文档 ("' get' 方法按名称查找) 了解更多信息,
我认为这是 Windsor 真正闪耀的地方之一:)
A better implementation, Windsor-wise, would be to utilize a typed factory. With a typed factory, your code would not have to reference the container, because a factory implementation would be automatically created for you.
With a typed factory, your factory could look like this:
and Windsor would forward each factory method to a corresponding resolve - e.g.
GetMove
would becomecontainer.Resolve<IUserInputCommand>("Move")
.See typed factory docs ("'get' methods lookup by name) for more information.
I think this is one of the places where Windsor really shines :)