LightInject 多个构造函数

LightInject multiple constructors

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

你可以使用 Typed Factories 来干净地完成这个。

http://www.lightinject.net/#typed-factories

Imports LightInject

Namespace Sample
    Class Program
        Private Shared Sub Main(args As String())
            Console.WriteLine("Go")

            Dim container = New ServiceContainer()
            container.Register(Of FooFactory)()

            Dim fooFactory = container.GetInstance(Of FooFactory)()
            Dim f1 As IFoo = fooFactory.Create()
            Dim f2 As IFoo = fooFactory.Create("Scott")
            Dim f3 As IFoo = fooFactory.Create(25)
            Dim f4 As IFoo = fooFactory.Create("Scott", 25)

            Console.WriteLine("Stop")
            Console.ReadLine()
        End Sub
    End Class

    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

    Public Class FooFactory

        Public Function Create() As IFoo
            Return New Foo()
        End Function

        Public Function Create(name As String) As IFoo
            Return New Foo(name)
        End Function

        Public Function Create(age As Integer) As IFoo
            Return New Foo(age)
        End Function

        Public Function Create(name As String, age As Integer) As IFoo
            Return New Foo(name, age)
        End Function
    End Class
End Namespace

注意,如果你觉得它增加了价值,你可以创建一个 IFooFactory 接口。