2010-03-08 22 views
0

即將升級到ASP.NET網站,我正在考慮使用Unity引入DI。我研究了ASP.NET的DI方面,並有2個選項(Global.asax或IHttpModule)。我很高興使用。當使用靜態方法時,使用Unity集成依賴注入的最佳方式是什麼?

一如既往,有一個遺留的對象模型,我想升級/更改。我想沿着Constructor注入的路線(傳入DAO),但是每個對象都有一些靜態和實例方法,它們都使用SqlCommand對象本身調用數據庫。我希望刪除這些數據庫以提供數據庫獨立性,因此任何人都可以提出在此情況下執行DI的最佳方法?如果需要的話,我可以改變。

public class ExampleClass 
{ 
     public ExampleClass(int test) 
     { 
      TestProperty = test; 
     } 

     public int TestProperty {get; set;} 

     public int Save() 
     { 
      // Call DB and Save 
      return 1; 
     } 

     public static ExampleClass Load(int id) 
     { 
      // Call DB and Get object from DB 
      return new ExampleClass(1); 
     } 

} 

感謝您的任何建議

馬特

回答

0

如果您刪除所有靜態方法,並介紹了一些抽象,你應該去的好:

public class ExampleClass 
{ 
    public int TestProperty { get; set; } 
} 

public interface IRepository 
{ 
    ExampleClass Load(int id); 
    int Save(); 
} 

public class RepositorySql: IRepository 
{ 
    // implement the two methods using sql 
} 

,並在你的ASP頁面:

private IRepository _repo = FetchRepoFromContainer(); 
public void Page_Load() 
{ 
    var someObj = _repo.Load(1); 
    // ... etc 
} 
+0

M y的意圖是使用企業庫4.1進行數據訪問。 DAO即時思考將主要用於將數據訪問分解爲功能區域。我也不認爲靜態方法可以在界面中定義?我真的在尋找一種使用靜態方法來使用DI的方法,或者在更好的方式上提供建議 – 2010-03-08 17:31:01

+0

無法在接口中定義靜態方法。 – 2010-03-08 17:32:08

+0

我在想,取消靜態將是要走的路。我只是希望避免它,因爲它會在有限的時間內完成很多工作,因爲整個站點也將被重寫。 – 2010-03-08 17:37:19

相關問題