博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Yet another way to manage your NHibernate ISessionFactory
阅读量:5334 次
发布时间:2019-06-15

本文共 2265 字,大约阅读时间需要 7 分钟。

So here is my current UnitOfWork implementation.  This one makes use of the somewhat new current_session_context_class feature. I think this is quite simple compared to some of the others you will find.

public interface IUnitOfWork : IDisposable    {        IUnitOfWork Start();        void BeginTransaction();        void CommitTransaction();        void RollbackTransaction(); }
public class UnitOfWork : IUnitOfWork    {        #region Dependencies        public ISessionFactory SessionFactory        {            get;            set;        }        #endregion #region IUnitOfWork Members public virtual void BeginTransaction() { var session = SessionFactory.GetCurrentSession(); if ( !session.Transaction.IsActive ) { session.BeginTransaction(); } } public virtual void CommitTransaction() { var session = SessionFactory.GetCurrentSession(); if ( session.Transaction.IsActive ) { session.Transaction.Commit(); } } public void RollbackTransaction() { var session = SessionFactory.GetCurrentSession(); if ( session.Transaction.IsActive ) { session.Transaction.Rollback(); } } public IUnitOfWork Start() { if ( !CurrentSessionContext.HasBind(SessionFactory) ) { var session = SessionFactory.OpenSession(); session.FlushMode = FlushMode.Commit; CurrentSessionContext.Bind(session); } return this; } #endregion #region IDisposable Members public void Dispose() { var session = CurrentSessionContext.Unbind(SessionFactory); var transaction = session.Transaction; if ( transaction.IsActive ) { transaction.Dispose(); } session.Dispose(); } #endregion }

 

All that’s required is this in the hibernate config section:

(for web apps):

web

(for pretty much anything else): 

thread_static

 

and just the barebones bootstrapping:

var sessionFactory = new Configuration().Configure().BuildSessionFactory();

Of course, to get this to work you need to register that sessionFactory instance into your IoC container, and register the UnitOfWork type with the container with a transient lifecycle.

 

From there you can either explicitly create and dispose IUnitOfWork instances for each operation, or set up a HttpModule to create one at the start of each request and dispose of it in the end_request event.

转载于:https://www.cnblogs.com/aaa6818162/p/4629904.html

你可能感兴趣的文章
NEYC 2017 游记
查看>>
[搬运] 写给 C# 开发人员的函数式编程
查看>>
Python之旅Day14 JQuery部分
查看>>
core--线程池
查看>>
redux-effect
查看>>
Swift和OC混编
查看>>
Android轻量级的开源缓存框架ASimpleCache
查看>>
他山之石:加载图片的一个小问题
查看>>
shell - 常识
查看>>
mssql sqlserver 使用sql脚本 清空所有数据库表数据的方法分享
查看>>
分层图最短路【bzoj2763】: [JLOI2011]飞行路线
查看>>
linux下编译复数类型引发的错误:expected unqualified-id before '(' token
查看>>
codeforces 1041A Heist
查看>>
字典常用方法
查看>>
Spring Cloud Stream消费失败后的处理策略(三):使用DLQ队列(RabbitMQ)
查看>>
python的猴子补丁monkey patch
查看>>
架构模式: API网关
查看>>
正则验证积累
查看>>
Linux学习-汇总
查看>>
83. 删除排序链表中的重复元素
查看>>