【发布时间】:2016-11-04 17:07:48
【问题描述】:
使用 LightInject 已经有一段时间了,感觉很棒!但是,在尝试支持相同类型的多个构造函数时遇到了麻烦。请参阅下面的简化示例。 Foo 有四个构造函数,不同的是参数的类型和数量。我为每个构造函数注册一个映射。我第一次调用 GetInstance 来检索 IFoo 时,它因以下异常而崩溃。我错过了什么?我怎样才能完成这个功能?
InvalidCastException:无法将“LightInject.ServiceContainer”类型的对象转换为“System.Object[]”类型。
Public Interface IFoo
End Interface
Public Class Foo
Implements IFoo
Public Sub New()
End Sub
Public Sub New(name As String)
End Sub
Public Sub New(age As Integer)
End Sub
Public Sub New(name As String, age As Integer)
End Sub
End Class
container.Register(Of IFoo, Foo)
container.Register(Of String, IFoo)(Function(factory, name) New Foo(name))
container.Register(Of Integer, IFoo)(Function(factory, age) New Foo(age))
container.Register(Of String, Integer, IFoo)(Function(factory, name, age) New Foo(name, age))
Dim f1 As IFoo = container.GetInstance(Of IFoo)() 'BOOM!
Dim f2 As IFoo = container.GetInstance(Of String, IFoo)("Scott")
Dim f3 As IFoo = container.GetInstance(Of Integer, IFoo)(25)
Dim f4 As IFoo = container.GetInstance(Of String, Integer, IFoo)("Scott", 25)
【问题讨论】:
-
您的
Foo类看起来不像是应该由您的DI 容器解析的组件;它似乎是一个实体或 DTO。像这样的对象不应该由您的 DI 容器解析,因为这只会导致歧义。
标签: dependency-injection light-inject