1

我應該如何在自定義模型活頁夾中正確實現數據訪問?在自定義模型綁定器中訪問數據存儲的正確方法是什麼?

與控制器中一樣,我使用IContentRepository,然後讓它在構造函數中創建實現類的實例。因此,我已經準備好在後期合併IoC(DI)。

現在我需要類似的模型活頁夾。我需要在活頁夾中進行一些數據庫查找。我正在考慮像我在控制器中那樣做,但我願意提出建議。

這是從我的控制器中的一個片段,所以你可以想像我是如何做它在其中:

 public class WidgetZoneController : BaseController 
     { 
// BaseController has IContentRepository ContentRepository field 
      public WidgetZoneController() : this(new XmlWidgetZoneRepository()) 
      { 
      } 

      public WidgetZoneController(IContentRepository repository) 
      { 
       ContentRepository = repository; 
      } 
    ... 

回答

0

您可以使用構造函數注入到您的自定義模型聯編程序類中,並且還可以從DefaultModelBinder繼承。

public class MyModelBinder : DefaultModelBinder 
{ 
    IContentRepository ContentRepository; 

    public MyModelBinder(IContentRepository contentRepository) 
    { 
     this.ContentRepository = contentRepository; 
    } 

通過自定義模型活頁夾,您註冊他們的Application_Start()這樣的:

protected void Application_Start() 
{ 
    System.Web.Mvc.ModelBinders.Binders.Add(
      typeof(MyModel), new MyModelBinder(contentRepository) 
    ); 

現在使用的IoC的時候,你需要記住你的對象的生命週期。當您將IoC與控制器配合使用時,每個Web請求都存在它們。因此,如果注入存儲庫,任何數據連接或OR/M會話都將在短時間內存在。

使用Model Binder,它基本上是一個長壽命的Singleton(Application_Start())。所以確保你的Repository在這兩種情況下都能正常工作。

相關問題