问题
I am using the Service/Repository/EF/POCO pattern in a MVC app, and had a couple questions about the Interfaces.
1) Should I make an Interface per Service? 2) Should I make an Interface per Repository?
Or, should I have a generic interface per layer (IService(Of T), IRepository(Of T)).
What I dont understand is how in the controller say, it takes a IService(Of Category) interface in it's constructor, how do I implements the methods in the concrete class?
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
The _Service does not have the methods of my concrete CategoryService class?
Make any sense?
回答1:
Use concrete interface for service. If your services can be described by generic interface you most probably don't need them at all. Generic interface is often used for repositories because repositories usually offer same core methods.
回答2:
For myself, I use a generic session object that is strongly type, this class is in my domain project witch contains all my domain classes. You should take a look at this post : http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx using Code-First approach.
Hope it helps!
Here my code for my Session class :
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
}
}
来源:https://stackoverflow.com/questions/5198008/question-about-interfaces-and-di