gpt4 book ai didi

vb.net - 依赖注入(inject) - 我不明白!

转载 作者:行者123 更新时间:2023-12-04 16:55:56 27 4
gpt4 key购买 nike

好的,所以我在玩 Ninject,一个“服务层”和一个“存储库层”。

我构建了一个简单的控制台应用程序来玩,这就是我想出的:

Imports Ninject

Module Module1

Sub Main()
Dim Kernel As IKernel = New StandardKernel(New CustomerModule)
Dim Service = Kernel.Get(Of CustomerService)()
Console.WriteLine(Service.GetCustomerByID(1).Name)
Console.Read()

End Sub

End Module

#Region "Services"

Public Class CustomerService
Private _Repository As ICustomerRepository

<Inject()> _
Public Sub New(ByVal Repository As ICustomerRepository)
_Repository = Repository

End Sub

Public Function GetCustomerByID(ByVal ID As Integer) As Customer
Return _Repository.GetByID(ID)
End Function

End Class

#End Region

#Region "Repositories"

Public Interface IRepository(Of T)
Function Query(ByVal Predicate As Expressions.Expression(Of Func(Of T, Boolean))) As IQueryable(Of T)
Function GetByID(ByVal ID As Integer) As T

End Interface

Public Interface ICustomerRepository
Inherits IRepository(Of Customer)

End Interface

Public Class CustomerRepository
Implements ICustomerRepository

Public Function GetByID(ByVal ID As Integer) As Customer Implements IRepository(Of Customer).GetByID
Return New Customer With {.ID = ID, .Name = "Sam Striano"}
End Function

Public Function Query(ByVal Predicate As System.Linq.Expressions.Expression(Of System.Func(Of Customer, Boolean))) As System.Linq.IQueryable(Of Customer) Implements IRepository(Of Customer).Query
Return Nothing
End Function

End Class

#End Region

#Region "Domain Objects"

Public Class Customer
Public Property ID As Integer
Public Property Name As String
End Class

#End Region

#Region "Ninject Modules"

Public Class CustomerModule
Inherits Modules.NinjectModule

Public Overrides Sub Load()
Bind(Of ICustomerRepository).To(Of CustomerRepository)()

End Sub

End Class

#End Region

我的问题,或者我猜我缺乏理解,在于模块的 Main() 方法:
Sub Main()
Dim Kernel As IKernel = New StandardKernel(New CustomerModule)
Dim Service = Kernel.Get(Of CustomerService)()
Console.WriteLine(Service.GetCustomerByID(710615).Name)
Console.Read()

End Sub

为什么不这样做:
Sub Main()
Dim Service = New CustomerService(New CustomerRepository)
Console.WriteLine(Service.GetCustomerByID(710615).Name)
Console.Read()

End Sub

最佳答案

基本上,您是在问为什么要使用 DI 容器 而不是 Pure DI .

DI 真的只是一个 一套原则和模式启用 松耦合 .您可以使用这些模式来编写应用程序 不考虑任何特定容器 .

但是,随着应用程序复杂性的增加,尤其是当您需要管理 时不同的生活方式在您的组件中,DI 容器是一个出色的工具,可以解决您必须手动解决的许多问题。

关于vb.net - 依赖注入(inject) - 我不明白!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5110814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com