我正在学习依赖注入。阅读了很多帖子并使用了一本书之后,下面的代码基于我所阅读的内容以及本书中的一个示例。这个控制台程序工作。在继续深入了解DI及其在单元测试中的应用之前,我想确认一下我是否正确理解它,以及我是否正确编码。
主要
Sub Main()
Dim myWriter As IMessageWriter 'myWriter must be same type as ConsoleMessageWriter, next line. That is INTERFACE type IMessageWriter
myWriter = New ConsoleMessageWriter() 'myWriter INSTANCE is required to construct MyConsoleWriter INSTANCE below
Dim myConsoleWriter As ConsoleWriter 'myConsoleWriter must be same type as ConsoleWriter, next line. That is CLASS type ConsoleWriter
myConsoleWriter = New ConsoleWriter(myWriter) 'myConsoleWriter INSTANCE contructed w/ myWriter INSTANCE. myConsoleWriter exposes ConsoleWrite
myConsoleWriter.ConsoleWrite("Hello DI world.", True) 'INSTANCE myConsoleWriter's ConsoleWrite method uses INSTANCE MyWriter's Write method
End Sub
ConsoleWriter
Public Class ConsoleWriter
Private ReadOnly writer As IMessageWriter
Public Sub New(writer As IMessageWriter)
If writer Is Nothing Then
Throw New ArgumentNullException("writer")
End If
Me.writer = writer
End Sub
Public Sub ConsoleWrite(message As String, pause As Boolean)
Me.writer.Write(message, pause)
End Sub
End Class
ConsoleMessageWriter
Public Class ConsoleMessageWriter
Implements IMessageWriter
Public Sub Write(message As String, pause As Boolean) Implements IMessageWriter.Write
If pause Then
Console.WriteLine(message)
Console.WriteLine("<press any key to continue>")
Console.ReadKey()
Else
Console.WriteLine(message)
End If
End Sub
End Class
IMessageWriter
Public Interface IMessageWriter
Sub Write(message As String, pause As Boolean)
End Interface
我在上面的代码中添加了注释,以提醒我为什么要采取每个步骤,下面的图片是我为了尝试理解这种方法而创建的图片。
我的问题很简单。代码有什么问题吗?代码中的注释?图形?关于代码,我理解可以组合几行,但我把它们分开以增强我的基本理解。
感谢。
答案 0 :(得分:1)
您的代码正确演示了依赖项注入的概念,您的图表正确演示了myConsoleWriter.ConsoleWrite
调用的执行方式。我唯一要改变的是你的评论myWriter must be same type as ConsoleMessageWriter, next line. That is INTERFACE type IMessageWriter
这不是很准确。 myWriter
不必是ConsoleMessageWriter
类型,它必须是实现IMessageWriter
的类型。因此,如果您有一个Public Class OtherConsoleMessageWriter Implements IMessageWriter
,那么myWriter
也可以是OtherConsoleMessageWriter
类型。
话虽如此,请确保您了解编写Main
方法的方式只是为了演示将依赖项注入ConsoleWriter
的概念,以及在实际程序中,不想做myWriter = New ConsoleMessageWriter()
。由于您正在学习依赖注入,我认为您尚未涉及DI容器的主题。它的要点是,您永远不想明确地创建依赖项,因为您将依赖项硬编码为特定类型(在您的情况下为ConsoleMessageWriter
)。 DI容器将允许您配置容器,以便您可以告诉它为每个接口返回哪种具体类型,然后让DI容器创建所有依赖项,但是您可以阅读更多内容。