I have a ASP.NET MVC4 web api that uses fluent NHibernate, but when I run debug it takes 1½ min to access any site that uses the database the first time I try, so I found Fluent nHibernate Slow Startup Time but I am not sure how to utilize that,
When it runs on the live server it must garbage collect the session data as it takes ages to configure again if I havent used it for a long time.
Is it possiible to cut it down to maybe sub 10 seconds instead of 1.5 minutes?
My current SessionFactory class looks like this
public class SessionFactory
{
private static readonly string ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString;
private static ISessionFactory _session;
private static readonly object SyncRoot = new Object();
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MySQLConfiguration
.Standard
.ConnectionString(ConnString))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<UserMap>())
.ExposeConfiguration(UpdateSchema)
.BuildSessionFactory();
}
private static void UpdateSchema(Configuration cfg)
{
new SchemaUpdate(cfg).Execute(false, true);
}
public static ISession Session
{
get
{
if (_session == null)
{
lock (SyncRoot)
{
if (_session == null)
_session = CreateSessionFactory();
}
}
return _session.OpenSession();
}
}
}
Here is a screenshot of a dotTrace
Timing the request on my host it takes 1 min and 50 seconds for the initial request, and thats on “live” server (I cant control the IIS there)
I can see a host of things wrong with this code. Your CreateSessionFactory should only ever be called once in the lifetime of your application. Create a static variable in global.asax and call CreateSessionFactory once in Application_Start(). Also in global.asax, you want to setup some events for Application_BeginRequest and Application_EndRequest. This is where you are going to create and destory sessions. This is your unit of work in a web application. You should also store your session in the HttpContext.
Your code recreates the SessionFactory every time you need a session.