通过 XML 配置 Unity 字典
如何使用 Unity 容器通过 XML 配置字典? 这可行:
<register type="System.Collections.Generic.Dictionary[string,int]" >
<constructor>
<param name="capacity">
<value value="10" />
</param>
</constructor>
</register>
但我需要能够在 XML 配置中添加元素。
How can I configure a dictionary via XML with Unity container?
This works:
<register type="System.Collections.Generic.Dictionary[string,int]" >
<constructor>
<param name="capacity">
<value value="10" />
</param>
</constructor>
</register>
But I need ability to add elements in XML config.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
上次我尝试这样做时,我必须使用自定义转换器并发明自己的字典值解析器。我不记得是哪个研究让我到达那里的,但这里是注册和相应的转换器类。
Last time I tried to do that I had to use a custom converter and invent my own parser for dictionary values. I don't remember which research got me there, but here is the registration and the corresponding converter class.
我相信您发布的配置存在几个问题:
您用来指定泛型类型的语法不正确。要指定 Dictionary 正确的语法应该是:
type="System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Int32, mscorlib]], mscorlib"
请注意,`2 指定泛型类型具有两个类型参数。
最后一点(也是个人偏好),我真的不喜欢使用 Unity 来创建此类对象。我通常使用自定义配置文件来进行任何重要的初始化设置,并严格使用 Unity 来注册依赖注入的类型映射。
I believe there are several problems with the configuration you have posted:
The syntax you are using to specify a generic type is not correct. To specify a Dictionary<string, int> the proper syntax should be:
type="System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Int32, mscorlib]], mscorlib"
Note the `2 designates the generic type as having two type parameters.
As a final note (and a personal preference), I'm really not a fan of using Unity for this type of object creation. I generally use a custom configuration file for any non-trivial initialization settings and use Unity strictly to register type mappings for dependency injection.
我自己没有尝试过,但您可能可以注册一堆 KeyValuePair 类的实例,然后在用作 IDictionary 构造函数参数的数组中引用它们。
I did not try it myself, but probably you can register a bunch of instances of KeyValuePair class, and then reference them in array used as an IDictionary constructor parameter.