Need a simple example of using nhibernate + unit of work + repository pattern + service layer + ninject

送分小仙女□ 提交于 2019-11-29 22:24:24

I'm using 'vanilla' ASP.NET, rather than ASP.NET MVC 3, but essentially we are doing the same things.

First off, I have a seperate UnitOfWork class like this:

public class UnitOfWork
{
    private static ISessionFactory SessionFactory
    {
        get
        {
            return Container.Get<ISessionFactory>();
        }
    }

    public static ISession Session
    {
        get
        {
            return SessionFactory.GetCurrentSession();
        }
    }

    public static void Start()
    {
        CurrentSessionContext.Bind(SessionFactory.OpenSession());
        Session.FlushMode = FlushMode.Commit;
        Session.BeginTransaction(IsolationLevel.ReadCommitted);
    }

    public static void Rollback()
    {
        Rollback(true);
    }

    /// <summary>
    /// Rollback the current transaction, and optionally start a new transaction
    /// </summary>
    /// <param name="startNew">Whether to start a new transaction and keep the session open</param>
    public static void Rollback(bool startNew)
    {
        ISession session = CurrentSessionContext.Unbind(SessionFactory);

        if (session != null)
        {
            // Rollback current transaction
            if (session.Transaction.IsActive && !session.Transaction.WasRolledBack)
            {
                session.Transaction.Rollback();
            }

            // Close and discard the current session
            session.Close();
            session.Dispose();
            session = null;
        }

        if (startNew)
        {
            Start();
        }
    }

    /// <summary>
    /// Commit the current transaction, keeping the current session open and starting a new transaction
    /// 
    /// Call Commit multiple times during a single unit of work if you want to commit database changes in
    /// multiple transactions
    /// </summary>
    public static void Commit()
    {
        Commit(true);
    }

    /// <summary>
    /// Commit the current transaction, and optionally keep the session open and start a new transaction
    /// 
    /// Call Commit multiple times during a single unit of work if you want to commit database changes in 
    /// multiple transactions
    /// </summary>
    /// <param name="startNew">Whether to start a new transaction and keep the session open</param>
    public static void Commit(bool startNew)
    {
        if (startNew)
        {
            Session.Transaction.Commit();
            Session.BeginTransaction(IsolationLevel.ReadCommitted);
        }
        else
        {
            ISession session = CurrentSessionContext.Unbind(SessionFactory);

            if (session != null)
            {
                if (session.Transaction.IsActive && !session.Transaction.WasRolledBack)
                {
                    session.Transaction.Commit();
                }

                session.Close();
                session.Dispose();
                session = null;
            }
        }
    }
}

I use an HTTP module to start a new unit of work for every web request, and to automatically commit/rollback. Not sure if you need an HTTP module when using ASP.NET MVC 3, or if there is some other way of doing it. Anyway, relevant parts shown below:

public class IoCHttpModule : IHttpModule, IDisposable
{
private HttpApplication httpApplication;

public void Init(HttpApplication context)
{
    if (context == null)
        throw new ArgumentException("context");

    this.httpApplication = context;

    this.httpApplication.BeginRequest += new EventHandler(BeginRequest);
    this.httpApplication.EndRequest += new EventHandler(EndRequest);
    this.httpApplication.Error += new EventHandler(Error);

    StandardIoCSetup.Initialise(SessionContextType.Web);
}

private void BeginRequest(object sender, EventArgs e)
{
    UnitOfWork.Start();
}

private void EndRequest(object sender, EventArgs e)
{
    UnitOfWork.Commit(false);
}

private void Error(object sender, EventArgs e)
{
    UnitOfWork.Rollback(false);
}

public void Dispose()
{
    if (this.httpApplication == null)
        return;

    this.httpApplication.Dispose();
}
}

So a new unit of work is started for every web request, and automatically committed if there are no unhandled exceptions. Of course, you can manually call UnitOfWork.Commit() or UnitOfWork.Rollback() within a web request, if required. The line StandardIoCSetup.Initialise... configures NHibernate using a Ninject module, much the same as you are already doing.

So in essence, it's not much work to add a unit of work to what you already have.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!