11

我試圖使用簡單注入器來創建我的存儲庫,並在業務邏輯層(也是我想使用PerWebRequest方法)中使用它。如何使用簡單注入器,存儲庫和上下文 - 代碼優先

在DAL層我有:

public interface IRepository<T> where T : class 
{ 
    void Add(T entity); 
    void Delete(T entity); 
    void Delete(int id); 
    void Update(T entity); 
    T GetById(int Id); 
    IQueryable<T> All(); 
    IEnumerable<T> Find(Func<T, bool> predicate); 
} 

和:

public class EFRepository<T> : IRepository<T>, IDisposable where T : class 
{ 
    #region Members 
    protected DbContext Context { get; set; } 
    protected DbSet<T> DbSet { get; set; } 
    #endregion 

    #region Constructors 

    public EFRepository(DbContext dbContext) 
    { 
     if (dbContext == null) 
      throw new ArgumentNullException("dbContext"); 
     Context = dbContext; 
     DbSet = Context.Set<T>(); 
    } 

和我的背景:

public class PASContext : DbContext, IDbContext 
{ 
    public DbSet<Product> Products { get; set; } 
    public DbSet<User> Users { get; set; } 

    public PASContext() 
     : base("PostAndSell") 
    { } 
} 

正如你可以看到EFRepository只有一個構造函數,它有一個參數 - 這是因爲我想使用Simple Injector來創建上下文和p的實例在創建時將其分配到存儲庫。

在BLL中,我有一個類ProductBLL,我想從數據庫中獲取該類中的所有產品(通過一些GetAll方法),並將其傳遞給HomeController。

我真的需要有人跟我說說這個。

我開始從nuger(簡單噴油器和簡單的注射器ASP.NET集成)

也在我的global.asax.cs文件安裝包右,下Application_Start()功能I`ve補充說:

var container = new SimpleInjector.Container(); 

container.RegisterPerWebRequest<IRepository<Product>, EFRepository<Product>>(); 

但我在哪裏創建上下文實例?以及如何在業務層訪問它?

回答

16

因爲你可能有很多IReposotory<T>實現(產品,客戶,員工等),最好做一個開放式泛型登記IRepository<T>這樣的:

container.Register(typeof(IRepository<>), typeof(EFRepository<>), Lifestyle.Scoped); 

凡範圍的生活方式被定義爲:

container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); 

此登記確保簡單的噴油器將返回一個EFRepository<Product>,每次請求IRepository<Product>時間,一個EFRepository<Customer>IRepository<Customer>等等,等等。

既然你想在同一個請求中所有存儲庫中使用的相同DbContext情況下,你也應該註冊DbContext與範圍的生活方式:

container.Register<DbContext, PASContext>(Lifestyle.Scoped); 

在BLL我有一個類ProductBLL我想所有的產品從數據庫中 並將它傳遞給,讓說的HomeController

在這種情況下,這似乎ProductBLL LIK對我來說是一種無用的抽象。如果它只是傳遞數據,那麼可以直接讓HomeController直接依賴IRepository<Product>

+0

謝謝,但如果我確實有BLL中的邏輯類,我該如何使用存儲庫?我的理念是BLL通過存儲庫與DAL進行對話,並通過類似productBLL的類與MVL進行BLL對話。另外,如果我想訪問HomeController中的這個存儲庫,我該怎麼做?當EF將創建數據庫? – jony89

+1

有一個BLL類只有當你有任何邏輯時纔有用。但是,如果您有邏輯,您當然需要將ProductBLL注入到您的控制器而不是產品中(或者如果添加的行爲僅僅是橫切關注點,例如日誌記錄,安全性,驗證等,您可以使用而不是IRepository上的裝飾器)。如果您想訪問控制器中的回購,您只需將IRepository 注入控制器;對此沒有任何幻想。這只是起作用。 – Steven

+0

,你可以看到我很漂亮。我如何簡單地將IRepository 「注入」到控制器中?什麼代碼與單詞「注入」有關?我如何訪問'productBLL'中的Repostiroy並將其注入控制器 - 請向我展示一些與此相關的代碼。另外,我仍然無法看到「PASContext」的實例傳遞給「EFRepository」構造函數......以及何時創建數據庫?因爲這是代碼優先的程序。 – jony89

相關問題