Session Management in Castle Active Record - nhibernate

How do I manage session if I am using Castle Active Record over nHibernate. Basically I can manage the life cycle of ISession on my own if I am using nHibernate directly. But when I am using Castle AR it does not give me a way to manage the life cycle of the session. I want to use single Session per thread.
I am using Castle AR in a WCF service and would like to use Session per WCF Request.

Instead of using ISession, in Castle ActiveRecord you want SessionScope:
using(new SessionScope())
{
; // do work here
}
If you need access to the ISession inside the SessionScope for some reason, you can do this:
ISession dbSession = Castle.ActiveRecord.ActiveRecordMediator
.GetSessionFactoryHolder().CreateSession(
typeof(Castle.ActiveRecord.ActiveRecordBase));
More documentation is here:
http://www.castleproject.org/activerecord/documentation/trunk/usersguide/scopes.html#sess_scope
and here:
http://www.castleproject.org/activerecord/documentation/trunk/manual/scopes.html

I assume you are working in a web app. Is that not the case?
There are a couple of ways to do it - Castle AR documentation
The simplest way is to the use SessionScopeWebModule to give a session per request.

Related

XSockets.Net - how to manage NHibernate Session Context

I wonder what is the best way to manage NHibernate Session Context
when using NH data layer from Xsockets controller.
Particularly I refer to self hosted winservice/console application or Azure worker role,
where HTTPContext is not available.
Of course there is always an option to create and dispose session per call, but that means a performance hit, so better reuse sessions in some way.
My controller provides API for CRUD operations in underlying NH repository and is pushing updates to relevant subscribers when certain records are updated in DB.
Your ideas appreciated :)
I'm using StructureMap to handle dependencies and create a NestedContainer to handle session per request. Don't have to mess with CurrentSessionContext or HttpContext anymore for storing session.
http://structuremap.github.io/the-container/nested-containers/
You could even just create a middleware UnitOfWork if you are using OWIN with WebAPI.
Since XSockets has state is will be bad for your database if you open the connection in the OnOpen event since the connection will remain open as long as the socket is open. Best is to use the repository only in the methods calling the CRUD operations as briefly as possible.
To get the instance of your repository should not be a bottleneck in this case.
I will be happy to review any code you might have.
Regards
Uffe

Castle Windsor/NHibernate/FactoryMethod and registering an NHIbernate EmptyInterceptor

I am using Castle Windsor for my IoC along with NHIbernate in an ASP.NET MVC app. It works great registered as follows:
container.Register(Component.For<ISessionFactoryBuilder.().ImplementedBy<SessionFactoryBuilder>().LifestyleSingleton());
// Register the NHibernate session factory as a singleton using custom SessionFactoryBuilder.BuildSessionFactory method.
container.Register(Component.For<ISessionFactory>().UsingFactoryMethod(k => k.Resolve<ISessionFactoryBuilder>().BuildSessionFactory("ApplicationServices")).LifestyleSingleton());
container.Register(Component.For<ISession>().UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession()).LifestylePerWebRequest());
However, I want to introduce an NHibernate IInterceptor in order to provide easy auditing. Typically I've used a NHibernate session manager in which it's easy to pass in an interceptor later on because SessionFactory.OpenSession(...) would typically be called in Begin_Request as opposed to "sort of" during component registration (which is in App_Start). Unfortunately, the LifestylePerWebRequest module can't be accessed at that point so for i.e., the following understandably fails:
container.Register(Component.For<IInterceptor>().ImplementedBy<ChangeAuditInfoInterceptor>().LifestylePerWebRequest());
var interceptor = container.Resolve<IInterceptor>();
container.Register(Component.For<ISession>().UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession(interceptor)).LifestylePerWebRequest());
What would be the best way to introduce an NHibernate Interceptor (which is usually inserted in SessionFactory.OpenSession(IInterceptor) when using this approach to NHibernate session management with Castle Windsor?
As stated in the comments, you should put the code to instantiate your interceptor in the lambda. This way, the code would execute on the right time :
container.Register(Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>()
.OpenSession(container.Resolve<IInterceptor>()))
.Lif‌​estylePerWebRequest());

ServiceStack and NHibernate Unit Of Work Pattern

Long story as brief as possible...
I have an existing application that I'm trying to get ServiceStack into to create our new API. This app is currently an MVC3 app and uses the UnitOfWork pattern using Attribute Injection on MVC routes to create/finalize a transaction where the attribute is applied.
Trying to accomplish something similar using ServiceStack
This gist
shows the relevant ServiceStack configuration settings. What I am curious about is the global request/response filters -- these will create a new unit of work for each request and close it before sending the response to the client (there is a check in there so if an error occurs writing to the db, we return an appropriate response to the client, and not a false "success" message)
My questions are:
Is this a good idea or not, or is there a better way to do
this with ServiceStack.
In the MVC site we only create a new unit
of work on an action that will add/update/delete data - should we do
something similar here or is it fine to create a transaction only to retrieve data?
As mentioned in ServiceStack's IOC wiki the Funq IOC registers dependencies as a singleton by default. So to register it with RequestScope you need to specify it as done here:
container.RegisterAutoWiredAs<NHibernateUnitOfWork, IUnitOfWork()
.ReusedWithin(ReuseScope.Request);
Although this is not likely what you want as it registers as a singleton, i.e. the same instance returned for every request:
container.Register<ISession>((c) => {
var uow = (INHibernateUnitOfWork) c.Resolve<IUnitOfWork>();
return uow.Session;
});
You probably want to make this:
.ReusedWithin(ReuseScope.Request); //per request
.ReusedWithin(ReuseScope.None); //Executed each time its injected
Using a RequestScope also works for Global Request/Response filters which will get the same instance as used in the Service.
1) Whether you are using ServiceStack, MVC, WCF, Nancy, or any other web framework, the most common method to use is the session-per-request pattern. In web terms, this means creating a new unit of work in the beginning of the request and disposing of the unit of work at the end of the request. Almost all web frameworks have hooks for these events.
Resources:
https://stackoverflow.com/a/13206256/670028
https://stackoverflow.com/search?q=servicestack+session+per+request
2) You should always interact with NHibernate within a transaction.
Please see any of the following for an explanation of why:
http://ayende.com/blog/3775/nh-prof-alerts-use-of-implicit-transactions-is-discouraged
http://www.hibernatingrhinos.com/products/nhprof/learn/alert/DoNotUseImplicitTransactions
Note that when switching to using transactions with reads, be sure to make yourself aware of NULL behavior: http://www.zvolkov.com/clog/2009/07/09/why-nhibernate-updates-db-on-commit-of-read-only-transaction/#comments

Is this a good solution to handle NHibernate Isession as PerWebRequest

I Have been struggeling with NHibernate session management and have now ended up with two possible solutions to meet a session per web request.
I'm using Windsor for IoC in an ASPNET mvc project
First solution is to open a session in begin_request and close/dispose it again in end_request. In Windsor setup I would have
container.Register(Component.For().UsingFactoryMethod(() => SessionFactory.GetCurrentSession()).LifeStyle.Transient;
This solution creates the session per request and shares it through GetCurrentSession.
The second solution is to use Windsor like
container.Register(Component.For().UsingFactoryMethod(() => SessionFactory.OpenSession()).LifeStyle.PerWebRequest);
This sould also give me an session per web request and support constructor injection. It's a bit more simpel, but I need a second opinion.
Please let me know what you would prefer to use,
best regards
Rasmus
I don't recommend any of those two solutions. Instead of trying to reinvent the wheel, use the NHibernate facility.
I use a unit of work, which I configure per web request in the container. The unit of work does not just create a session, but it also commits and rolls back transactions. The main reason to use a unit of work is to make the database more stable. More information about the unit of work pattern can be found on here.
public interface INHiberanteUnitOfWork
{
ISession session { get; }
void Commit();
void RollBack();
}

nhibernate and sessions, please clarify

I am building a web application, and whenever I make a database call I need a session.
I understand creating a session object is very expensive.
I am following the repository pattern here: http://web.archive.org/web/20110503184234/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx
He uses something called a UnitOfWork to get the session.
For a web application, shouldn't I be storing the Session in Request.Items collection? So its only created once per request?
Do I really need UofW?
The session IS the unit of work - its basically used to store changes until you flush them to the db. Save a static session factory at startup, and use that to create one session per web request - Request.Items seems a valid place to put the session.
The repository pattern is a wrapper over the unit of work. The repository pattern differs from the UoW pattern in that repo.Save(obj) should save the obj to the db straight away, while the UoW waits for a flush.
My advice would be to skip the repository pattern and use the ISession directly (see http://ayende.com/Blog/archive/2009/04/17/repository-is-the-new-singleton.aspx)
In the case of NHibernate the key class is the SessionFactory, which SessionProvider is taking care of for you (if you implement it like that). Keep the SessionFactory alive, and it handles the sessions for you.
I've also seem people save the SessionFactory in their IoC.
Use this to manage your sessions:
HybridSessionBuilder
It manages and gives you access to a single session that's used across the entire application.