Question

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!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top