How to increase web application performance with asp.net mvc3 and nhibernate

I am developing my first application using mmc3 nhibernate orm layer with mssql db.

This is my first application created using nhibernate, and everything is fine except for intuitive time. After some research, I completed a session for each web request, which is certainly an update, my objects load much faster after the first call, but my problem remains the same.

The initial response time is very slow, when I type domainname.com and press enter, the wait time is approx. 10-15 sec and this is not the actual time for loading the content, after that time 10-15 seconds. my site starts loading, a few more seconds.

This is the time during which the factory session should initialize all the “things” that are needed, but I think it should be something else. This is unacceptable.

My application runs on winhost when allocating memory on a 200 MB site, so I think this is not a problem.

Any hints are welcome. If you need more information, please ask.

thank

Update: After learning how to use an application session with the nhibernate profiler, I found some interesting material. Since I'm really starting to use the profiler, I think I found an expensive session. In general statistics, 67 objects are loaded in 36.571 durations in seconds. This seconds value is really strange because I have 10-max. 15 seconds to download.

Second update: global.asax

public class MvcApplication : System.Web.HttpApplication{     

public static ISessionFactory SessionFactory =
        MyDomain.Infrastructure.SessionProvider.CreateSessionFactory();

//My session factory is open in Application_Start() like this 
SessionFactory.OpenSession();

}

. , :

//This should be used from web app, global.asax.cs calls
        public static ISessionFactory CreateSessionFactory()
        {
            string conStringName = "ConnectionString";
            var cfg = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                .ConnectionString(c => c.FromConnectionStringWithKey(conStringName)))
                .Mappings(m => m.FluentMappings.Add<Entity1>())
                .Mappings(m => m.FluentMappings.Add<Entity2>())
                .Mappings(m => m.FluentMappings.Add<Entity3>())
                .ExposeConfiguration(p => p.SetProperty("current_session_context_class", "web"))
                .BuildConfiguration();

            return cfg.BuildSessionFactory();            
        }

3

4 sessionFactory. , . - , , , , . / . .

+3
4

, , NHibernate, :

  • NH SessionFactory ( , @Rippo ). SessionFactory . Application_Start()
  • NH -. . NH ISession / . , ISession . , , .
  • (NH LINQ? QueryOver? ) . .ToList() 20. Skip/Take.
  • SELECT N + 1. OR/M.

, .

:, 10-15 , , , SessionFactory Application_Start.

, - NH Configuration ( ) ( ). , , ( ).

Fluent NHibernate FluentNHibernate.Cfg.FluentConfiguration cfg.BuildSessionFactory() , ISessionFactory. , , - NHibernate.Cfg.Configuration. , , , - :

    public static ISessionFactory CreateSessionFactory()
    {
        string conStringName = "ConnectionString";

        // http://weblogs.asp.net/ricardoperes/archive/2010/03/31/speeding-up-nhibernate-startup-time.aspx
        System.Runtime.Serialization.IFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        NHibernate.Cfg.Configuration cfg = null;

        if (File.Exists("Configuration.serialized"))
        {
            using (Stream stream = File.OpenRead("Configuration.serialized"))
            {
                cfg = serializer.Deserialize(stream) as Configuration;
            }
        }
        else
        {
            // file not exists, configure normally, and serialize NH configuration to disk
            cfg = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                .ConnectionString(c => c.FromConnectionStringWithKey(conStringName)))
                .Mappings(m => m.FluentMappings.Add<Entity1>())
                .Mappings(m => m.FluentMappings.Add<Entity2>())
                .Mappings(m => m.FluentMappings.Add<Entity3>())
                .ExposeConfiguration(p => p.SetProperty("current_session_context_class", "web"))
                .BuildConfiguration();

            using (Stream stream = File.OpenWrite("Configuration.serialized"))
            {
                serializer.Serialize(stream, cfg);
            }
        }

        return cfg.BuildSessionFactory();
    }

, . , NH-, Fluent Configuration, .

:

  • .Mappings(m = > m.FluentMappings.Add()). (m = > m.FluentMappings.Add()) .. , HBM . .Mappings(M = > M.FluentMappings.AddFromAssemblyOf())
  • , SessionFactory.OpenSession() Application_Start(). SessionFactory SessionFactory.GetCurrentSession() . global.asax :

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // we open one NH session for every web request, 
        var nhsession = SessionFactory.OpenSession();
        // and bind it to the SessionFactory current session
        CurrentSessionContext.Bind(nhsession);
    }
    
    protected void Application_EndRequest(object sender, EventArgs e)
    {
        // close/unbind at EndRequest
        if (SessionFactory != null)
        {
            var nhsession = CurrentSessionContext.Unbind(SessionFactory);
            nhsession.Dispose();
        }
    }
    

.

+12

: -

  • - bin? , factory.
  • SQL, NHProf Management Studio, . ?
  • TRIPLE , factory , Application_start

SQL-, , NHibernate !

, , , , ANTI profiler ( 14 )

+3

@raulg . :

  • NH . Google .
  • NHibernate! . log4net , , "" NHibernate, perf .
  • Beware of using not.lazyload in mappings - you can end up loading your entire database into a query without understanding! Desired request loading if necessary.

Stick to it - a great tool.

NH serialization:

  if (_loadConfiguration && _configurationFile.Exists && _IsConfigurationFileValid())
            {
                configuration = _LoadConfigurationFromFile();
            }
            else
            {
                configuration = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008
                        .ConnectionString(x => x.FromConnectionStringWithKey("Development"))
                        #if DEBUG
                        .ShowSql()
                        #endif
                    )
                    .ProxyFactoryFactory("NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate")
                    .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<UserMap>()
                                              .Conventions.Setup(MappingConventions.GetConventions()))
                    .Mappings(mappings => mappings.HbmMappings.AddFromAssemblyOf<UserMap>())
                    .BuildConfiguration();

                _SaveConfigurationToFile(configuration);
            }

  private bool _IsConfigurationFileValid()
        {
            var assInfo = new FileInfo(Assembly.GetCallingAssembly().Location);
            return _configurationFile.LastWriteTime >= assInfo.LastWriteTime;
        }

        private void _SaveConfigurationToFile(Configuration configuration)
        {
            //#if DEBUG
            //return;
            //#endif
            _logger.Debug("Starting to save NHibernate configuration to " + _configurationFile.FullName);
            using(var file = _configurationFile.OpenWrite())
            {
                new BinaryFormatter().Serialize(file, configuration);
                file.Close();
            }
            _logger.Debug("Finished saving NHibernate configuration to " + _configurationFile.FullName);
        }

        private Configuration _LoadConfigurationFromFile()
        {
            //#if DEBUG
            //    return null;
            //#endif
            _logger.Debug("Starting to load NHibernate configuration from " + _configurationFile.FullName);
            using(var file = _configurationFile.OpenRead())
            {
                var binaryFormatter = new BinaryFormatter();
                var config = binaryFormatter.Deserialize(file) as Configuration;
                file.Close();
                _logger.Debug("Finished loading NHibernate configuration from " + _configurationFile.FullName);
                return config;
            }
        }
+2
source
+1
source

All Articles