2011-08-10 129 views
0

我想配置Unity来将一个接口(比如说ITest)解析为一个结构,比如struct Test。到目前为止,我有未来:是否可以将结构绑定到Unity中的接口?

<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)) 

为什么?

回答

0

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

例如:

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

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

我建议改为一个类的实现,而不是一个结构。

+1

为什么'Activator.CreateInstance'不能够创建一个结构? – Lee

+0

我测试了这一点;当结构体上有一个接口时,CreateInstance调用失败。不明原因。 – Tejs

+1

'Int32'实现了许多接口,工作正常。 – Lee

相关问题