2011-03-04 50 views
0

我在MVC應用程序中使用Service/Repository/EF/POCO模式,並對接口有幾個問題。有關接口和DI的問題?

1)我應該爲每個服務創建一個接口嗎? 2)我應該爲每個存儲庫創建一個接口嗎?或者,我應該有每層通用接口(IService(Of T),IRepository(Of T))。

我不明白的是如何在控制器中說,它的構造函數需要一個IService(Of Category)接口,我該如何實現具體類中的方法?

Public Class HomeController 
    Inherits System.Web.Mvc.Controller 

    Private _Service As IService(Of Category) 

    Public Sub New(ByVal Service As IService(Of Category)) 
     _Service = Service 

    End Sub 

    Function Index() As ActionResult 

     Return View() 
    End Function 

End Class 

_Service沒有具體的CategoryService類的方法嗎?

有意義嗎?

回答

1

使用具體界面進行維修。如果你的服務可以用通用接口來描述,你可能根本不需要它們。通用接口通常用於存儲庫,因爲存儲庫通常提供相同的核心方法。

+0

謝謝!你會描述服務層中的接口還是我的情況,我正在描述MyProject.Core.dll中的存儲庫接口? – Sam 2011-03-04 19:28:03

+0

@Sam:我可能不明白你的問題。你問你應該把這些接口放在哪裏? – 2011-03-04 19:31:08

+0

是的,我應該在哪裏放?我是否應該將Repository接口放在Repository層和服務層的Service Interfaces中,還是應該將它們全部放入一個區域,如MyProject.Core區域? - 謝謝! – Sam 2011-03-04 20:59:24

0

對於我自己,我使用強類型的泛型會話對象,該類在我的域項目巫婆包含我所有的域類。你應該看看這個職位:http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx使用代碼優先的方法。

希望它有幫助!

這裏我的代碼爲我的Session類:

public class EFSession : ISession 
{ 
    DbContext _context; 

    public EFSession(DbContext context) 
    { 
     _context = context; 
    } 


    public void CommitChanges() 
    { 
     _context.SaveChanges(); 
    } 

    public void Delete<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new() 
    { 

     var query = All<T>().Where(expression); 
     foreach (var item in query) 
     { 
      Delete(item); 
     } 
    } 

    public void Delete<T>(T item) where T : class, new() 
    { 
     _context.Set<T>().Remove(item); 
    } 

    public void DeleteAll<T>() where T : class, new() 
    { 
     var query = All<T>(); 
     foreach (var item in query) 
     { 
      Delete(item); 
     } 
    } 

    public void Dispose() 
    { 
     _context.Dispose(); 
    } 

    public T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new() 
    { 
     return All<T>().FirstOrDefault(expression); 
    } 

    public IQueryable<T> All<T>() where T : class, new() 
    { 
     return _context.Set<T>().AsQueryable<T>(); 
    } 

    public void Add<T>(T item) where T : class, new() 
    { 
     _context.Set<T>().Add(item); 
    } 

    public void Add<T>(IEnumerable<T> items) where T : class, new() 
    { 
     foreach (var item in items) 
     { 
      Add(item); 
     } 
    } 

    /// <summary> 
    /// Do not use this since we use EF4, just call CommitChanges() it does not do anything 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="item"></param> 
    public void Update<T>(T item) where T : class, new() 
    { 
     //nothing needed here 
    } 
}