2017-08-29 41 views
0

我有一個使用DbContext添加和插入產品產品邏輯類。StructureMap - EF初始化可變從另一個類

我還有一個ProductImporter類,它循環訪問文件中的產品列表並調用Product類中的addProduct。它在交易中這樣做,因此所有產品都添加或沒有。僞在下面。

產品類有兩個構造函數。第一個接受dbcontext,第二個初始化一個新的dbcontext。我使用第一個構造函數來傳遞ProductImporter中的DbContext以啓用事務。

var dbContext... 

ImportProducts() { 

    Product p = new Product(dbContext); 

    dbContext.BeginTransaction 


    While(moreProducts) 

     p.addProduct(); 


    End transaction 

} 

我的問題是:我該如何使用結構圖來滿足這兩種情況

  1. 注入產品類的新實例,每當應用程序需要添加一個產品。

  2. 在上述ImportProducts方法中注入Product類以使用相同的DbContext。實際上,通過結構圖替換下面的行來注入產品類並使其與ProductImporter類使用相同的DbContext

    Product p = new Product(dbContext); 
    

感謝。

回答

0

沒有對任何類的,我只能推測代碼 - 但似乎你是混合數據類和邏輯/服務類 - 這可以引領你進入難以維持和難以落實的問題(後者是什麼你正在經歷)。

我的建議是讓你的產品類只保存數據 - 沒有邏輯可言。您可以使用存儲庫模式來執行此操作。我找到了一個鏈接,給你一個例子:http://web.archive.org/web/20150404154203/https://www.remondo.net/repository-pattern-example-csharp/

請仔細閱讀上面的鏈接和研究模式 - 它會爲你節省大量的時間和頭痛。如果你理解了這種模式,請查看通用知識庫他們將爲您節省更多時間,並使您的代碼更容易維護。

這裏的關鍵是你有一個單獨的類爲數據/實體/模型和邏輯/服務/(使用數據庫)的另一個類。

然後你只需要你的資料庫有DbContext注入和存儲庫可以注射給進口商。

例如:

這是未經測試和即興代碼。我只是試圖提供一個解決方案的例子。

public class ProductImporter 
{ 
    private readonly IProductRepository _productRepository;  

    public ProductImporter(IProductRepository productRepository) 
    { 
     this.__productRepository = this._productRepository; 
    } 

    public void AddProducts(IEnumerable<Product> products) 
    { 
     foreach(var product in products) 
     { 
      this._productRepository.Add(product); 
     } 
    } 
    ... 
}