是否可以将结构绑定到 Unity 中的接口?
我想要配置 Unity 将接口(如 ITest
)解析为结构(如 struct Test
)。到目前为止我有下一个:
<unity>
<containers>
<container>
<types>
<type
type="my.ITest, asm"
mapTo="my.Test, asm">
</type>
</types>
</container>
</containers>
</unity>
但我收到下一个错误:
Resolution of the dependency failed, type = "my.ITest", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Test cannot be constructed. You must configure the container to supply this value.
At the time of the exception, the container was:
Resolving my.Test,(none) (mapped from my.ITest,(none))
为什么?
I want configure Unity to resolve an interface, say ITest
, to a struct, say struct Test
. So far I have next:
<unity>
<containers>
<container>
<types>
<type
type="my.ITest, asm"
mapTo="my.Test, asm">
</type>
</types>
</container>
</containers>
</unity>
but I'm getting next error:
Resolution of the dependency failed, type = "my.ITest", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Test cannot be constructed. You must configure the container to supply this value.
At the time of the exception, the container was:
Resolving my.Test,(none) (mapped from my.ITest,(none))
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你正在尝试使用 Unity 来构造一个结构体;因为结构体是值类型,所以 Activator.CreateInstance 在尝试创建它时会破坏块(因为接口)。
例如:
会抛出异常“无法创建接口的实例”。在内部,Unity 可能在链下游的某个地方使用 Activator.CreateInstance(我已经浏览了 Unity 的代码丛一段时间了),这就是它会死掉的地方。
我建议更改为类实现而不是结构。
The problem is that you are trying to use Unity to construct a struct; because a struct is a value type, Activator.CreateInstance is going to blow chunks when trying to create it (because of the interface).
For example:
Would throw an exception "Cannot create an instance of an interface". Internally, Unity is probably using Activator.CreateInstance somewhere down the chain (I've been looking through Unity's code plex for a little while now), and that's where it will die.
I'd suggest changing to a class implementation instead of a struct.
Unity 仅支持类绑定。
Unity supports only binding of classes.