光照多个构造函数



使用LightInject已经有一段时间了,它非常棒!但是,在尝试支持同一类型的多个构造函数时遇到了一个障碍。请参阅下面的简化示例。Foo有四个构造函数,不同的是参数的类型和数量。我为每个构造函数注册一个映射。当我第一次调用GetInstance来检索IFoo时,它出现了以下异常。我错过了什么?我怎样才能完成这个功能呢?

InvalidCastException:无法强制转换LightInject类型的对象。

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)

您可以使用类型化工厂来干净利落地完成此任务。

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接口。

相关内容

  • 没有找到相关文章

最新更新