Search code examples
nhibernateapp-configconfigurationmanager

How to load application settings to NHibernate.Cfg.Configuration object?


How to load application settings to NHibernate.Cfg.Configuration object by using System.Configuration.ConfigurationManager from App.config?


Solution

  • app.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="Northwind" connectionString=
           "Data Source=(local);Initial Catalog=Northwind;Trusted_Connection=True;>
      </connectionStrings>
    </configuration>
    

    C# code:

    string connectionString =  System.Configuration.ConfigurationManager
                                     .ConnectionStrings["Northwind"].ToString();
    
    NHibernate.Cfg.Configuration nHibernateConfiguration =
                                          new NHibernate.Cfg.Configuration();
    nHibernateConfiguration.SetProperty(
      NHibernate.Cfg.Environment.ProxyFactoryFactoryClass,
      typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName);
    nHibernateConfiguration.SetProperty(
      NHibernate.Cfg.Environment.Dialect,
      typeof(NHibernate.Dialect.MsSql2005Dialect).AssemblyQualifiedName);
    nHibernateConfiguration.SetProperty(
      NHibernate.Cfg.Environment.ConnectionString, connectionString);
    nHibernateConfiguration.SetProperty(
      NHibernate.Cfg.Environment.FormatSql, "true");
    nHibernateConfiguration.AddAssembly(Assembly.GetCallingAssembly());
    
    ISessionFactory oneISessionFactory = nHibernateConfiguration
                                            .BuildSessionFactory();