I created a web api only project with asp.net 5 and trying to set up my NHibernate session management. Everything seems to be fine but inside my controller when I try to use the session, I get a null exception although I mark it with NHibernateSession
attribute.
I realized that the method does not use the session created by the attribute. What should I do to make it use that one ? Any suggestions are greatly appreciated.
public class ValuesController : Controller
{
private readonly IRepository _repository;
public ISessionContainer NHibernateSession { get; set; }
public ValuesController(IRepository repository)
{
_repository = repository;
}
// GET: api/values
[HttpGet, NHibernateSession]
public IEnumerable<string> Get()
{
return _repository.GetProducts(); // session is null exception
}
}
public class NHibernateSessionAttribute: ActionFilterAttribute
{
protected ISessionContainer sessionContainer;
public NHibernateSessionAttribute()
{
sessionContainer = new NHibernateSessionContainer();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
sessionContainer.OpenSession();
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
sessionContainer.CloseSession();
}
}
public class NHibernateSessionContainer : ISessionContainer
{
public static ISessionFactory SessionFactory = CreateSessionFactory();
private ISession _session;
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(OracleClientConfiguration.Oracle10
.ConnectionString(ConfigurationManager.ConnectionStrings["Main.ConnectionString"].ConnectionString))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.BuildConfiguration().BuildSessionFactory();
}
public ISession Session
{
get { return _session; }
}
public void OpenSession()
{
_session = SessionFactory.OpenSession();
}
public void CloseSession()
{
Dispose();
}
public void Dispose()
{
_session.Dispose();
}
}
services.AddSingleton<ISessionContainer, NHibernateSessionContainer>();
services.AddTransient<IRepository, Repository>();