作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的,所以我在玩 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
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/
我是一名优秀的程序员,十分优秀!