1

I'm new to IoC and NHibernate, and am having a great deal of difficulty trying to get my head around best practices for dependency injection. I've spent the last couple of days looking around and reading documentation, but unfortunately the documentation I've found has been either obsolete or incomplete.

For instance, this tells me what to do, I but I have no idea how to do it. XSockets.Net - how to manage NHibernate Session Context

I have learned that, according to the official documentation, I need to use nested containers in structuremap to make sure that sessions are created and disposed appropriately for each request. Unfortunately the examples are all set within unit tests that construct their own container. I have no idea how to apply this to MVC.

If I have a repository like this

public class Repository : IRepository {    
    public Repository(ISession session) {
        ...
    }
    ...
}

How do I make this work:

public NHibernateRegistry()    
{
    ISessionFactory factory = config.BuildSessionFactory();
    For<IRepository>.Use<Repository>()
    For<ISession>.????????
}

Or have I got it all backwards somehow?

Community
  • 1
  • 1
mike1952
  • 493
  • 5
  • 12
  • Here is a blog post describing it for other injection framework, but it should be useful http://slynetblog.blogspot.com/2012/03/using-aspnet-mvc-4-webapi-with.html – Sly Apr 22 '16 at 08:55
  • Hi Sly, thanks for the link. The line `builder.Register(x => x.Resolve().OpenSession()).InstancePerHttpRequest();` is the thing that I know I want to execute but can't figure out how to translate to structuremap. – mike1952 Apr 22 '16 at 09:22

1 Answers1

0

So, it turns out that this behaviour is automatic - I don't need to switch it on. I was making an unrelated error and thought that this was the problem. It isn't helped by somewhat unclear documentation. If you are using the structuremap.MVC5 nuget package then:

SessionFactory _factory;
public NHibernateRegistry()    
{
    _factory = config.BuildSessionFactory();
    For<IRepository>.Use<Repository>()
    For<ISession>.Use(() => _factory.OpenSession());
}

This will cause structuremap to open a session once per httprequest. Of course, you shouldn't open the session here, as there are a bunch of things relating to transactions, binding and unit of work stuff that you'll want to handle properly - but that's a separate NHibernate thing that is beyond the scope of this problem.

mike1952
  • 493
  • 5
  • 12