0

The problem I'd like to solve is sharing an ISessionProvider between IXyzRepositories (where ISessionProvider holds the current NHibernate ISession).

I'm tweaking the "Setting up session per presenter" recipe from NHibernate 3 Cookbook, and would like to keep StructureMap (brownfield project).

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
Martin R-L
  • 4,039
  • 3
  • 28
  • 28

2 Answers2

1

I think you would have to create a custom Lifecyle to do that, although I am not sure what exactly you are trying to accomplish...

To create a custom Lifecycle, you just have to implement the ILifecycle interface and the use it in your registration. Here is an example you can look at: http://blog.mikeobrien.net/2010/01/creating-structuremap-lifecycle-for-wcf.html.

Robin Clowers
  • 2,150
  • 18
  • 28
1

In a web application I use Singleton for the sessionFactory and HybridHttpOrThreadLocalScoped for the session: This is my structuremap registry:

public class NhibernateRegistry: Registry
{
    public NhibernateRegistry()
    {
        For<ISessionFactory>()
        .Singleton()
        .Use(new NHibernateSessionFactory(connectionString).SessionFactory);

        For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Use(o => o.GetInstance<ISessionFactory>().CurrentSession);
    }
}

My NHibernateSessionFactory is similar to SessionProvider class used in the book. Everything is disposed at the end of the request (web app):

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

I use a generic repository:

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private readonly ISession _session;

    public GenericRepository(ISession session)
    {
        _session = session;
    }

    public T Load(Guid Code)
    {
        return (_session.Load<T>(Code));
    }

}

but you can easily change it with your own implementation. I register the repository here:

public class RepositoriesRegistry : Registry
{
    public RepositoriesRegistry()
    {
        For <Data.IRepository<Domain.Reminder, Guid>>()
            .HybridHttpOrThreadLocalScoped()
            .Use<Data.NH.Repository<Domain.Reminder, Guid>>();
    }
}
Community
  • 1
  • 1
LeftyX
  • 35,328
  • 21
  • 132
  • 193