【问题标题】:Is it possible to bind a struct to an interface in Unity?是否可以将结构绑定到 Unity 中的接口?
【发布时间】:2011-08-10 20:11:35
【问题描述】:

我想配置 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))

为什么?

【问题讨论】:

    标签: c# .net struct unity-container ioc-container


    【解决方案1】:

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

    例如:

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

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

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

    【讨论】:

    • 为什么Activator.CreateInstance 不能创建结构体?
    • 我对此进行了测试;当结构上有接口时, CreateInstance 调用失败。不知道为什么。
    • Int32 实现了许多接口并且工作正常。
    • 不知道该告诉你什么。我做了一个简单的例子; public struct ConcreteSomething : ISomething { },然后调用Activator.CreateInstance&lt;ConcreteSomething&gt;,它抛出了一个错误。
    • @tejs - 什么版本的.net?接口 I { } 结构 S : I{ } static void Main(string[] args) { I o = Activator.CreateInstance(); } 对我来说很好(.net4)
    【解决方案2】:
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多