繁体   English   中英

是否可以将结构绑定到 Unity 中的接口?

[英]Is it possible to bind a struct to an interface in 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))

为什么?

问题是您正在尝试使用 Unity 构造一个结构; 因为结构是值类型,所以 Activator.CreateInstance 在尝试创建它时会破坏块(因为接口)。

例如:

 var item = Activator.CreateInstance<Test>();

会抛出异常“无法创建接口的实例”。 在内部,Unity 可能在链的某个地方使用了 Activator.CreateInstance(我已经查看了 Unity 的代码 plex 有一段时间了),这就是它会死的地方。

我建议更改为 class 实现而不是结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM