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

发布于 2024-11-29 05:18:43 字数 855 浏览 1 评论 0原文

我想要配置 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千鲤 2024-12-06 05:18:43

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

例如:

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

会抛出异常“无法创建接口的实例”。在内部,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:

 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.

I'd suggest changing to a class implementation instead of a struct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文