views:

192

answers:

2

Hi,

I just started using StructureMap in my MVC apps, and everything goes fine, excepts handling my ITranscation the correct way.

What I want to do is create a new ISession on each request. Together with this I want to start a transcation.

On the end of the request I will commit the transcation.

My question is, how can I do this the best way with StructureMap. I found a lot of examples on Google, but none of them starts a transcation with the request, and I really don't want to do this in my methods.

Thanks in advance!

+1  A: 

It's probably not that easy but here is my take. Create a unit of work that basically wraps the session and transaction and store that away for the request and commit or rollback when the request is over.

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

Implementation could then look like:

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 dispose the unit of work at endrequest.

mhenrixon
That look exactly what I need, thanks!Should I then just call Commit() and dispose on EndRequest in my IHttpModule?
J. Hovgaard
Yes, don't try to dispose the transaction after you committed it though (it disposes after commit). Just the unit of work.
mhenrixon
+2  A: 

These two articles should help.

http://trason.net/journal/2009/10/7/bootstrapping-nhibernate-with-structuremap.html

http://trason.net/journal/2009/10/14/nhibernate-transactional-boundaries.html

Kristoffer Ahl
The second link looks very interesting. I'll get back to you. Thanks so far.
J. Hovgaard
+1 for Weston's blog.
mxmissile
http://trason.net/journal/2009/10/14/nhibernate-transactional-boundaries.html was an awesome post! :)
J. Hovgaard