简体   繁体   中英

Repository pattern, UoW pattern, plain NHibernate Session

There are many discussions about use of Repository pattern , UoW pattern . I quite understand when and why Repository pattern is used. Let's just say I have several aggregate roots. What's next? What pattern/implementation do I prefer? What are the reasons to use more complex solutions than plain NHibernate Session?

Thanks!

Repository pattern is an abstraction that is -imho- not unnecessary. It just allows you to predefine certain queries that can be used multiple times throughout the system, and, it improves readability imho.

The repository uses the unit-of-work (which is already implemented by NHibernate's ISession ); that's my point of view.

What I would do, is create some extension methods on NHibernate's ISession for your project; which can look like this:

public class ISessionExtensions
{
    public static IEmployeeRepository GetEmployeeRepository( this ISession session )
    {
         return new EmployeeRepository(session);
    }
}

public class EmployeeRepository()
{
    internal EmployeeRepository( ISession s )
    {
    }

    public IEnumerable<Employee> GetEmployeesFromDepartment( Department d )
    {
      ...
    }
}

Then, in your code, you can do this:

using( ISession s = _sessionFactory.OpenSession() )
{
    var repository = s.GetEmployeeRepository();
    ...
}

Repository pattern is before NHibernate. Now we apply repository pattern on top of NHibernate which is unnecessary abstraction in most cases. The idea behind a generic repository as an abstraction layer over NHibernate is that at some point you can switch to other persisting mechanism like Entity Framework. Really? Is that possible? I think not, because you will end up with so many NH specifics like caching, fetching etc. For me plain Session usage is OK.

Here ayende talks about that for a while
And more...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM