4

I'm new to NHibernate and I'm trying to impelement Generic Repository Pattern and Unit of Work for using in an ASP.NET MVC 3 application. I googled the title and found new links; but all of them was more complexe to understanding by me. I use StructureMap as my IOC. Can you suggest me some links or blog posts please?

amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • 1
    NHibernate's ISession already represents a unit of work and access to a repository. – Andre Loker Mar 04 '12 at 16:59
  • A repository should encapsulate the data access layer, that is it will use but it will NOT expose Nhibernate. And a proper designed repository (for your needs, a generic repository is useless) should not need unit of work either – MikeSW Mar 04 '12 at 19:09

2 Answers2

5

Here are a couple of items to read thru:

The implementation I have used in my most recent project looked like:

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
    T GetByID(int id);
    T GetByID(Guid key);
    void Save(T entity);
    void Delete(T entity);
}

public class Repository<T> : IRepository<T>
{
    protected readonly ISession Session;

    public Repository(ISession session)
    {
        Session = session;
    }

    public IEnumerable<T> GetAll()
    {
        return Session.Query<T>();
    }

    public T GetByID(int id)
    {
        return Session.Get<T>(id);
    }

    public T GetByID(Guid key)
    {
        return Session.Get<T>(key);
    }

    public void Save(T entity)
    {
        Session.Save(entity);
        Session.Flush();
    }

    public void Delete(T entity)
    {
        Session.Delete(entity);
        Session.Flush();
    }
}
Community
  • 1
  • 1
Jesse
  • 8,223
  • 6
  • 49
  • 81
  • Thanks; I got it. But now, how can I create an `ISession` object via injection? `public Repository(ISession session)` but it seems that the `ISession` can be created by `OpenSession` method only; for example, how to work with this repository via StructureMap? can more explain please? – amiry jd Mar 04 '12 at 19:15
  • 1
    @king.net I myself use ninject over structure map, however similar concepts would apply. Within ninject I would do something like this: Bind().ToMethod(x => NHibernateHelper.OpenSession()).InRequestScope(); – Jesse Mar 04 '12 at 19:27
1

Check out this solution - https://bitbucket.org/cedricy/cygnus/overview

Its a simple implementation of a Repository pattern that we've used in our production MVC 1, 2, and 3 applications.

Of course, we've learned since then that we really appreciate having our queries run directly against ISession. You have more control over them that way. That and Ayende told us not too.

Thanks Cedric!

shanabus
  • 12,989
  • 6
  • 52
  • 78