2
votes

I'm developing an web application with asp.net mvc 2, and I'm using NHibernate (session per request) and Unity (for dependency injection).

In my Global.asax I'm managing my ISession something like this:

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();
}

Nice, and In my Repositories (in constructor) I pass the SessionFacotry (static in global.asax) e get ISession by SessionFacotry.GetCurrentSession(). My repositories I inject in the contrcutor's controllers! Great...

But, in my asp.net mvc application I have a value in cache and a CacheRemovedItem delegate with this Cache. In this method (in delegate), I need to persist some informations in my reopsitories, but I don't have a request when the cache expires. I'd like to know how could I RESOLVE my dependencies in this method (CacheItemRemoved delegate) in right way ? Or How could I setup an ISession to get via GetCurrentSession() in SessionFactory ?

PS: Sorry for my English!

1
Where do you store the container? In a HttpModule? Why the session factory is not resolved via container? - onof
HI Onof, The container and session factory are static on the global.asax. I initialize in Application_Start event. In my repositories I get the session via GetCurrentSEssion (because I setup my session per request via ManagedWebSessionContext.Bind and ManagedWebSessionContext.Unbind. So, Need I setup this in my method ? - Felipe Oriani

1 Answers

0
votes

Seems that what you need is to use SessionFactory.GetCurrentSession()

For that:

1- Configure it in the configuration file on the current_session_context_class property to web:

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

2- Use CurrentSessionContext.Bind(session); in your BeginRequest and CurrentSessionContext.Unbind(sessionFactory); in your EndRequest

Hope it helps.