[英]Is it possible to bind a struct to an interface in Unity?
I want configure Unity to resolve an interface, say ITest
, to a struct, say struct Test
.我想配置 Unity 以将接口(例如
ITest
)解析为结构(例如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?为什么?
The problem is that you are trying to use Unity to construct a struct;问题是您正在尝试使用 Unity 构造一个结构; because a struct is a value type, Activator.CreateInstance is going to blow chunks when trying to create it (because of the interface).
因为结构是值类型,所以 Activator.CreateInstance 在尝试创建它时会破坏块(因为接口)。
For example:例如:
var item = Activator.CreateInstance<Test>();
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.
在内部,Unity 可能在链的某个地方使用了 Activator.CreateInstance(我已经查看了 Unity 的代码 plex 有一段时间了),这就是它会死的地方。
I'd suggest changing to a class implementation instead of a struct.我建议更改为 class 实现而不是结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.