I am trying to use the Unity IoC with the unit of work & repository patterns, however I’m struggling to work out how my repository would get it’s Nhibernate session to perform it’s work…
Below I have my IUnityContainer which does my IoC bindings.. I then have my NHibernate repo which needs to be provided with a ISession, which should be provided from the NHibernate unit of work, but I am now sure how I can tell Unity to provide it in it’s constructor..
I have made a binding for the IUnitOfWork to a Nhib… one, but how does one pass that value in the IRepository RegisterType?
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
NHibernateHelper helper = new NHibernateHelper();
// register all your components with the container here
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterControllers();
container.RegisterType<IUnitOfWork, NHibernateUnitOfWork>(new HierarchicalLifetimeManager());
container.RegisterInstance<ISessionFactory>(helper.SessionFactory);
container.RegisterType<IRepository, NHibernateRepository>() ;
return container;
}
public class NHibernateRepository : IRepository
{
public NHibernateRepository(ISession session)
{
_session = session;
}
}
public class NHibernateUnitOfWork : IUnitOfWork
{
private readonly ISessionFactory _sessionFactory;
private readonly ITransaction _transaction;
public ISession Session { get; private set; }
public NHibernateUnitOfWork(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
Session = _sessionFactory.OpenSession();
Session.FlushMode = FlushMode.Auto;
_transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
}
}
Register your
ISessionwith yourIUnityContainerlike so:Then when an
ISessionis required, anISessionFactorywill be resolved and a session started.In the applications I work on, we define our repositories and unit of work like so:
Then your services use it something like this: