0

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

1 回答 1

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 接口增加了价值,则可以创建它。

于 2016-11-04T17:55:58.540 回答