I\'m in the process of designing my ASP.NET MVC application and I ran across a couple of interesting thoughts.
Many samples I have seen describe and use the Reposito
Here is how I'm using it. I'm using IRepository for all the operations that are common to all of my repositories.
public interface IRepository where T : PersistentObject
{
T GetById(object id);
T[] GetAll();
void Save(T entity);
}
and I use also a dedicated an ITRepository for each aggregate for the operation that are distinct to this repository. For example for user I will use IUserRepository to add method that are distinct to UserRepository:
public interface IUserRepository : IRepository
{
User GetByUserName(string username);
}
The implementation will look like this:
public class UserRepository : RepositoryBase, IUserRepository
{
public User GetByUserName(string username)
{
ISession session = GetSession();
IQuery query = session.CreateQuery("from User u where u.Username = :username");
query.SetString("username", username);
var matchingUser = query.UniqueResult();
return matchingUser;
}
}
public class RepositoryBase : IRepository where T : PersistentObject
{
public virtual T GetById(object id)
{
ISession session = GetSession();
return session.Get(id);
}
public virtual T[] GetAll()
{
ISession session = GetSession();
ICriteria criteria = session.CreateCriteria(typeof (T));
return criteria.List().ToArray();
}
protected ISession GetSession()
{
return new SessionBuilder().GetSession();
}
public virtual void Save(T entity)
{
GetSession().SaveOrUpdate(entity);
}
}
Than in the UserController will look as:
public class UserController : ConventionController
{
private readonly IUserRepository _repository;
private readonly ISecurityContext _securityContext;
private readonly IUserSession _userSession;
public UserController(IUserRepository repository, ISecurityContext securityContext, IUserSession userSession)
{
_repository = repository;
_securityContext = securityContext;
_userSession = userSession;
}
}
Than the repository is instantiated using dependency injection pattern using custom controller factory. I'm using StructureMap as my dependency injection layer.
The database layer is NHibernate. ISession is the gateway to the the database in this session.
I'm suggest you to look on CodeCampServer structure, you can learn a lot from it.
Another project that you can learn fro it is Who Can Help Me. Which I don't dig enough in it yet.