How can I implement NHibernate session per request without a dependency on NHibernate?

Posted by Ben on Stack Overflow See other posts from Stack Overflow or by Ben
Published on 2010-05-26T12:34:08Z Indexed on 2010/05/26 12:41 UTC
Read the original article Hit count: 552

I've raised this question before but am still struggling to find an example that I can get my head around (please don't just tell me to look at the S#arp Architecture project without at least some directions).

So far I have achieved near persistance ignorance in my web project. My repository classes (in my data project) take an ISession in the constructor:

public class ProductRepository : IProductRepository
{
    private ISession _session;
    public ProductRepository(ISession session) {
        _session = session;
    }

In my global.asax I expose the current session and am creating and disposing session on beginrequest and endrequest (this is where I have the dependency on NHibernate):

    public static ISessionFactory SessionFactory = CreateSessionFactory();

    private static ISessionFactory CreateSessionFactory() {
        return new Configuration() 
            .Configure()
            .BuildSessionFactory();
    }

    protected MvcApplication()  {
        BeginRequest += delegate {
            CurrentSessionContext.Bind(SessionFactory.OpenSession());
        };
        EndRequest += delegate {
            CurrentSessionContext.Unbind(SessionFactory).Dispose();
        };
    }

And finally my StructureMap registry:

    public AppRegistry() {
        For<ISession>().TheDefault
            .Is.ConstructedBy(x => MvcApplication.SessionFactory.GetCurrentSession());

        For<IProductRepository>().Use<ProductRepository>();
    }

It would seem I need my own generic implementations of ISession and ISessionFactory that I can use in my web project and inject into my repositories?

I'm a little stuck so any help would be appreciated.

Thanks, Ben

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about nhibernate