簡體   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