Build StructureMap / NHibernate per request, including persistent transcription

I just started using StructureMap in my MVC applications and everything is going fine except that I am processing my ITranscation .

What I want to do is create a new ISession for each request. Along with this, I want to start transcription.

At the end of the request, I will pass the transcription.

My question is: how can I do this in the best way with StructureMap. I found many examples on Google, but none of them started transcribing with the request, and I really do not want to do this in my methods.

Thanks in advance!

+4
source share
2 answers

This is probably not so simple, but here's my trick. Create a unit of work that basically ends the session and transaction and saves it for the request, and also commits or rolls back after the request is completed.

 public interface IUnitOfWork : IDisposable { ISession Session { get; } void Commit(); void Rollback(); } 

The implementation may look like this:

 public class UnitOfWork : IUnitOfWork { private readonly ITransaction _tx; public ISessionFactory SessionFactory { get; set; } public UnitOfWork() { SessionFactory = ObjectFactory.GetNamedInstance<ISessionFactory>(Keys.SessionFactoryName); Session = SessionFactory.OpenSession(); _tx = Session.BeginTransaction(); } public UnitOfWork(ISessionFactory sessionFactory) { SessionFactory = sessionFactory; Session = SessionFactory.OpenSession(); _tx = Session.BeginTransaction(); } public ISession Session { get; private set; } public void Commit() { if (_tx.IsActive) _tx.Commit(); } public void Rollback() { _tx.Rollback(); } } 

Just remove the unit of work with endrequest.

+1
source

All Articles