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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.