0

MVC アプリで Service/Repository/EF/POCO パターンを使用していますが、インターフェイスについていくつか質問がありました。

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 クラスのメソッドがありませんか?

意味がありますか?

4

2 に答える 2

1

サービスには具体的なインターフェースを使用します。あなたのサービスが一般的なインターフェイスで記述できる場合、おそらくそれらはまったく必要ありません。リポジトリは通常同じコアメソッドを提供するため、リポジトリには汎用インターフェースがよく使用されます。

于 2011-03-04T18:59:30.193 に答える
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
    }
}
于 2011-03-04T21:44:57.000 に答える