【问题标题】:Resolve Method with Unity用 Unity 解决方法
【发布时间】:2011-04-10 18:32:26
【问题描述】:

我正在使用 asp.net mvc 2 开发一个 Web 应用程序,并且我正在使用 NHibernate(每个请求的会话)和 Unity(用于依赖注入)。

在我的 Global.asax 中,我正在管理我的 ISession,如下所示:

public override void Init()
{
    base.Init();

    BeginRequest += OpenNHibernateSession;
    EndRequest += DisposeNHibernateSession;
}

private static void OpenNHibernateSession(object sender, EventArgs e)
{            
    ManagedWebSessionContext.Bind(HttpContext.Current, _sessionFactory.OpenSession());
}

private static void DisposeNHibernateSession(object sender, EventArgs e)
{
    var session = ManagedWebSessionContext.Unbind(HttpContext.Current, _sessionFactory);

    if (session != null)
        session.Dispose();
}

很好,并且在我的存储库中(在构造函数中),我通过 SessionFacotry(在 global.asax 中为静态)并通过 SessionFacotry.GetCurrentSession() 获取 ISession。我将我的存储库注入到 contrcutor 的控制器中!太好了……

但是,在我的 asp.net mvc 应用程序中,我在缓存中有一个值,并且有一个带有此缓存的 CacheRemovedItem 委托。在这种方法中(在委托中),我需要在我的存储库中保留一些信息,但是当缓存过期时我没有请求。我想知道如何以正确的方式解决我在此方法(CacheItemRemoved 委托)中的依赖关系?或者 如何设置 ISession 以通过 SessionFactory 中的 GetCurrentSession() 获取

PS:对不起我的英语!

【问题讨论】:

  • 您将容器存放在哪里?在 HttpModule 中?为什么会话工厂没有通过容器解析?
  • 您好 Onof,容器和会话工厂在 global.asax 上是静态的。我在 Application_Start 事件中初始化。在我的存储库中,我通过 GetCurrentSEssion 获取会话(因为我通过 ManagedWebSessionContext.Bind 和 ManagedWebSessionContext.Unbind 为每个请求设置会话。所以,我需要在我的方法中设置它吗?

标签: asp.net-mvc nhibernate caching domain-driven-design unity-container


【解决方案1】:

看来你需要的是使用 SessionFactory.GetCurrentSession()

为此:

1- 在配置文件中将 current_session_context_class 属性配置到 web:

<property name="current_session_context_class">web</property>

2- 使用 CurrentSessionContext.Bind(session);在您的 BeginRequest 和 CurrentSessionContext.Unbind(sessionFactory);在您的 EndRequest 中

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多