簡體   English   中英

實施通用存儲庫和工作單元模式

[英]Implementing the generic repository and unit of work patterns

我正在嘗試根據本教程實現通用存儲庫和工作單元模式。 除了這些模式之外,我還使用Ninject為我的Web應用程序進行依賴項注入。

我使用的特定綁定在這里:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind(typeof(IGenericRepository<>))
          .To(typeof(GenericRepository<>)).InSingletonScope();
    kernel.Bind<IUnitOfWork>()
          .To<UnitOfWork>();
}

但是根據教程,我需要將DbContext傳遞給UnitOfWork類中的每個存儲庫屬性,以便所有存儲庫僅共享一個DbContext實例,如下所示:

public GenericRepository<Course> CourseRepository
{
    get
    {
        if (this.courseRepository == null)
        {
            this.courseRepository = new GenericRepository<Course>(context);
        }
        return courseRepository;
    }
}

問題是,每當Ninject注入GenericRepository的實例時,如何將DbContext實例(位於UnitOfWork類中)傳遞給GenericRepository構造函數? 我知道WithConstructorArgument方法,但是不能在我的kernel.Bind調用中使用它,因為kernel.Bind我將無法訪問DbContext實例。

恕我直言,您的問題不是依賴性注入解決問題,而是創建GenericRepository對象時的實例依賴性(您需要dbcontext的特定實例,該實例依賴於正在解析IGenericRepository的UnityOfWork類)

因此,我建議您使用工廠來創建IGenericRepository實例。

您可以在此處找到更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM