加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在不依赖NHibernate的情况下为每个请求实现N

发布时间:2020-12-16 04:04:54 所属栏目:asp.Net 来源:网络整理
导读:我之前提出过这个问题,但我仍然在努力寻找一个可以让我理解的例子(请不要只是告诉我在没有至少一些指示的情况下查看S#arp架构项目). 到目前为止,我已经在我的网络项目中实现了近乎持久的无知.我的存储库类(在我的数据项目中)在构造函数中使用了一个ISession
我之前提出过这个问题,但我仍然在努力寻找一个可以让我理解的例子(请不要只是告诉我在没有至少一些指示的情况下查看S#arp架构项目).

到目前为止,我已经在我的网络项目中实现了近乎持久的无知.我的存储库类(在我的数据项目中)在构造函数中使用了一个ISession:

public class ProductRepository : IProductRepository
{
    private ISession _session;
    public ProductRepository(ISession session) {
        _session = session;
    }

在我的global.asax中,我公开当前会话,并在beginrequest和endrequest上创建和处理会话(这是我对NHibernate的依赖):

public static ISessionFactory SessionFactory = CreateSessionFactory();

    private static ISessionFactory CreateSessionFactory() {
        return new Configuration() 
            .Configure()
            .BuildSessionFactory();
    }

    protected MvcApplication()  {
        BeginRequest += delegate {
            CurrentSessionContext.Bind(SessionFactory.OpenSession());
        };
        EndRequest += delegate {
            CurrentSessionContext.Unbind(SessionFactory).Dispose();
        };
    }

最后我的StructureMap注册表:

public AppRegistry() {
        For<ISession>().TheDefault
            .Is.ConstructedBy(x => MvcApplication.SessionFactory.GetCurrentSession());

        For<IProductRepository>().Use<ProductRepository>();
    }

看来我需要我自己的ISession和ISessionFactory的通用实现,我可以在我的web项目中使用它并注入我的存储库?

所以只是为了澄清 – 我在我的存储库层使用NHibernate并希望使用session-per-(http)请求.因此,我将一个ISession注入到我的存储库构造函数中(使用structuremap).目前,为了在每个请求中创建和处理会话,我必须从我的web项目中引用NHibernate.这是我想要删除的依赖项.

谢谢,

解决方法

为什么不创建IHttpModule并在那里执行创建和处理(可能在Begin_Request和End_Request事件中),但是将IHttpModule放在具有NHibernate依赖性的项目中.例如.
namespace MyWebApp.Repository.NHibernateImpl
{
    public class NHibernateModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Context_BeginRequest);
            context.EndRequest += new EventHandler(Context_EndRequest);
        }

        private void Context_BeginRequest(object sender,EventArgs e)
        {
            // Create your ISession
        }

        private void Context_EndRequest(object sender,EventArgs e)
        {
            // Close/Dispose your ISession
        }

        public void Dispose()
        {
            // Perhaps dispose of your ISessionFactory here
        }
    }
}

也许有更好的方法,我也有兴趣知道这一点,所以任何其他建议?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读