Another common method for configuring NHibernate uses a separate xml configuration file. In this recipe, I'll show you how to configure NHibernate using hibernate.cfg.xml
to provide an identical configuration to the previous recipe.
Eg.Core
model and mapping recipes from Chapter 1.ConfigByXML
.ConfigByXML
project, add references to NHibernate.dll
and NHibernate.ByteCode.Castle.dll
in the Lib
folder.ConfigByXML
, add a reference to the Eg.Core
project.App.config
file with this configuration:<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="db" connectionString="Server=.SQLExpress; Database=NHCookbook; Trusted_Connection=SSPI"/> </connectionStrings> </configuration>
hibernate.cfg.xml
with this XML:<?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="proxyfactory.factory_class"> NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle </property> <property name="dialect"> NHibernate.Dialect.MsSql2008Dialect, NHibernate </property> <property name="connection.connection_string_name"> db </property> <property name="adonet.batch_size"> 100 </property> <mapping assembly="Eg.Core"/> </session-factory> </hibernate-configuration>
Program.cs
and add using NHibernate.Cfg;
.Main
function, add the following code to configure NHibernate:var nhConfig = new Configuration().Configure(); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate Configured!"); Console.ReadKey();
This recipe works in the same way as the previous recipe. We still use the db
connection string defined in the App.config
. However, in this recipe, we've moved the hibernate-configuration
element from the App.config
file to hibernate.cfg.xml
. Just as with the mappings, we get full IntelliSense from the schema file we added to the solution back in Chapter 1. We change Copy to Output Directory to ensure that our hibernate.cfg.xml
file is copied with the build output.
By default, NHibernate looks for its configuration in the hibernate.cfg.xml
. However, we can specify a different configuration file using the following code:
var cfgFile = "cookbook.cfg.xml"; var nhConfig = new Configuration().Configure(cfgFile);
Additionally, we can embed our configuration file in the assembly. In this case, we pass in the assembly
containing the resource as well as the embedded resource name.
Finally, we can pass an XmlReader
to provide our configuration from any other source.
18.118.93.64