I am trying to pass my unitofwork into my generic base repository, but when i try and call some of the methods the unitofwork isnt being passed into the base repository.
The scenario: I inject the userRepository below into my UserController all fine, its when it calls the userRepository.Save(user) it fails due to the unitofwork being null. Im not sure why though?
Im using nhibernate and structuremap. I think ive wired everything up correctly but here is some code to double check:
Here is the base repository:
public class BaseRepository<T> : IRepository<T> where T : IAggregateRoot
{
private readonly IUnitOfWork _unitOfWork;
public BaseRepository(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public BaseRepository()
{}
public void Save(T Entity)
{
_unitOfWork.Session.Save(Entity);
}
}
A specific repository:
public class UserRepository : BaseRepository<User>, IUserRepository
{
}
This is my nhibernate structuremap configuration:
public NhibernateRegistry()
{
For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();
For(typeof(IRepository<>)).Use(typeof(BaseRepository<>));
// Nhibernate Session
For<ISession>().HybridHttpOrThreadLocalScoped().Use(context => context.GetInstance<ISessionFactory>().OpenSession());
// Nhibernate SessionFactory
For<ISessionFactory>().Singleton().Use(NhibernateHelper.CreateSessionFactory());
}`
Here is my nhibernate http module:
public class NHibernateModule : IHttpModule
{
private IUnitOfWork _unitOfWork;
public void Init(HttpApplication context)
{
context.BeginRequest += ContextBeginRequest;
context.EndRequest += ContextEndRequest;
}
private void ContextBeginRequest(object sender, EventArgs e)
{
_unitOfWork = ObjectFactory.GetInstance<IUnitOfWork>();
}
private void ContextEndRequest(object sender, EventArgs e)
{
try { _unitOfWork.Commit(); }
catch { _unitOfWork.Rollback(); }
finally { Dispose(); }
}
public void Dispose()
{
if (_unitOfWork != null)
_unitOfWork.Dispose();
}
}
UserRepository needs a constructor that takes in the IUnitOfWork and passes it to the BaseRepository constructor. Currently, UserRepository is using the parameterless constructor of BaseRepository, so no IUnitOfWork is injected. Get rid of the parameterless constructor, and make sure all derived types pass the IUnitOfWork to the base.