LightInject多个构造函数

时间:2016-11-04 17:07:48

标签: dependency-injection light-inject

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

1 个答案:

答案 0 :(得分:0)

您可以使用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接口。