gpt4 book ai didi

asp.net-mvc - Entity Framework 上下文 - 我卡住了!

转载 作者:行者123 更新时间:2023-12-04 17:40:29 32 4
gpt4 key购买 nike

好的,所以我之前已经对此提出了一些问题,但我真的只是花了很长时间才理解这一点。

我正在使用 Service/Repository/EF 4 w/Pocos 方法,并且我设置了 Ninject 并将服务注入(inject) Controller ,但我试图找出在哪里注入(inject)上下文?

我希望能够在 Controller 上使用多个服务,而这些服务又可以使用相同的上下文访问多个存储库,因此所有更改都将一次持久化。

我研究了 UnitOfWork 模式,但我不明白 MVC( Controller )如何实现这一点,因为他们只知道服务层和域实体。

编辑

正如 Mohamed 下面建议的那样,将上下文注入(inject)存储库,然后使用它的每个请求实例。如何在 MVC 应用程序中配置绑定(bind)?我会假设是这样的:

Bind(Of IContext).To(MyDataContext)

问题是,MVC 应用程序对上下文一无所知,对吧?

编辑 2
Public Class ProductController
Private _Service As IProductService

Public Sub New(Service As IProductService)
_Service = Service
End Sub

End Class

Public Class NinjectWebModule

Public Sub New()
Bind(Of IProductService).To(ProductService)
End Sub

End Class

Public Interface IProductService

End Interface

Public Class ProductService
Implements IProductService

Private _Repository As IRepository(Of Product)

Public Sub New(Repository As IRepository(Of Product))
_Repository = Repository
End Sub

End Class

Public Class NinjectServiceModule

Public Sub New()
Bind(Of IRepository(Of Product)).To(EFRepository(Of Product))
End Sub

End Class

Public Interface IRepository(Of T As Class)

End Interface

Public Class EFRepository(Of T As Class)
Implements IRepository(Of T)

Private _UnitOfWork As MyUnitOfWork

Public Sub New (UnitOfWork As IUnitOfWork)
_UnitOfWork = UnitOfWork
End Sub

End Class

Public Class NinjectRepositoryModule

Public Sub New()
Bind(Of IUnitOfWork).To(EFUnitOfWork).InRequestScope()
End Sub

End Class

Public Interface IUnitOfWork
Sub Commit()
End Interface

Public Class EFUnitOfWork()
Implements IUnitOfWork

Public Property Context As MyContextType

Public Sub New()
_Context = New MyContextType
End Sub

End Class

然后我会从 MVC 应用程序注册所有三个模块吗?

最佳答案

您需要的组件:

  • 存储库(通用或特定)
  • 工作单位
  • 服务
  • Controller

  • 每个是什么:
  • 存储库:针对提供的上下文执行查询
  • 工作单元:包装 Entity Framework ObjectContext
  • 服务:调用存储库上的方法
  • Controller :在服务上调用方法,并在工作单元上调用“提交”。

  • 与此一致,您的 Controller 的 ctor 应如下所示:
    public ProductController(IUnitOfWork unitOfWork, IProductService productService)

    您需要 UoW,因为您提到要跨多个存储库进行更改(一个相当常见的场景)。因此,通过将 UoW(即底层的 ObjectContext)传递给存储库,您可以启用它。

    使用 DI 容器将工作单元设置为 范围为 Http 上下文。

    关于asp.net-mvc - Entity Framework 上下文 - 我卡住了!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5216012/

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