I am looking to get some feedback on how I can improve my design. Specifically, I don’t want to have to create a new repository object for each of my domain objects but I also do not want to rewrite the Session and Transaction logic over and over.
To alleviate the need to write the code to obtain a new session and transation for every database transaction I make I created and generic abstract class that looks like this:
public class AbstractNHibernate<T> where T : class
{
public void Add<T>(T entity)
{
using(ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
}
}
}
Thats great but then I have to create a repository for each of my domain entities like so:
public class ConnectionModel : AbstractNHibernate<Connection>
{
public void SaveConnection(Connection conn)
{
Add(conn);
}
}
I could potentially have many of these. Can someone suggest a different approach?
Thanks in advance.
Your repositories should (in general) not open sessions or perform transactions. That should be done in a service layer or the UI. With your current design there’s no way to have multiple repositories participate in the same transaction. You can accomplsh this by requiring the ISession in the repository constructor.
I also dislike the one repository per object model, a better approach is to logically group together common repository functions. For example, a CompanyRepository would have methods for working with companies and related data — CompanyType, CompanyStatus, etc.