1

I am implementing an NHibernate Session Factory in a WebAPI 2 project that uses OWIN. Below is a snippet of my startup class. I notice that the Startup is being called each time I load a page in my debug environment. This seems very expensive and SessionFactory should only be created once per application lifetime.

How do I avoid this? I think the repeated calls is causing problems. I am getting errors that seem related to the session factory being created multiple times within OWIN.

Public Class Startup
    Public Sub Configuration(app As IAppBuilder)
        GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)

        app.CreatePerOwinContext(AddressOf MobLib.MobDataProvider.CreateProvider)

    End Sub
End Class

Update I've confirmed that Configuration is only running once, but calls to CreateProvider are occurring every time the page loads. Is this by design?

Origin
  • 1,943
  • 13
  • 33
  • Hope you're not calling Configuration method of Startup class method by yourself from somewhere because it's auto-detectable. – vendettamit Apr 17 '15 at 20:51
  • `Configuration` is not explicitly called anywhere, only by detection. – Origin Apr 17 '15 at 21:38
  • Can you replicate this in a POC and share it? I would really want to know why this is happening because this is not usual. – vendettamit Apr 17 '15 at 23:46
  • Digging into it now. I was just hoping this was a stupid mistake that others had made and could enlighten me :) – Origin Apr 18 '15 at 09:35

1 Answers1

3

I'm going to answer my own question instead of deleting it to hide my shame - I mean, for posterity!

Everything is behaving as it should, and CreatePerOwinContext is quite literally doing exactly what it says. It calls the function each time a context is created. This is not what you want for something heavy like an NHibernate SessionFactory - especially because this can result in multiple Session Factories. I somehow thought the OWIN Context was where I should store this Singleton object, when it absolutely is not.

This makes the real question: should I put initialization code in the OWIN Startup method, or the Global.asax file. That is a completely different question, which can be seen many places. For example: Do I need a Global.asax.cs file at all if I'm using an OWIN Startup.cs class and move all configuration there?

Community
  • 1
  • 1
Origin
  • 1,943
  • 13
  • 33