实体框架背景 - 我被困住了!

Sam*_*Sam 5 asp.net-mvc

好的,所以我之前就这个问过几个问题,但我真的只是想了解这一点.

我正在使用Service/Repository/EF 4 w/Pocos方法,我有Ninject设置并向控制器注入服务,但我试图找出注入上下文的位置?

我希望能够在控制器上使用多个服务,这些服务又可以使用相同的上下文访问多个存储库,因此所有更改都将立即保留.

我研究了UnitOfWork模式,但我不明白MVC(控制器)如何实现它,因为他们只知道服务层和域实体.

编辑

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

Bind(Of IContext).To(MyDataContext)
Run Code Online (Sandbox Code Playgroud)

问题是,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
Run Code Online (Sandbox Code Playgroud)

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

RPM*_*984 7

您需要的组件:

  1. 存储库(通用或特定)
  2. 工作单位
  3. 服务
  4. 控制器

每个是什么:

  1. 存储库:针对提供的上下文执行查询
  2. 工作单元:包装Entity Framework ObjectContext
  3. 服务:在Repository上调用方法
  4. 控制器:调用Services上的方法,并在Unit of Work上调用"Commit".

有了这个,你的Controller的ctor应该是这样的:

public ProductController(IUnitOfWork unitOfWork, IProductService productService)
Run Code Online (Sandbox Code Playgroud)

您需要UoW,因为您提到要在多个存储库中进行更改(这是一种相当常见的方案).因此,通过将UoW(它是引擎盖下的ObjectContext)传递给存储库,您可以启用它.

使用DI容器将工作单元设置为Http Context作用域.