We can also configure NHibernate entirely in code. In this recipe, I'll show you how to use the NHibernate.Cfg.Loquacious
namespace to configure NHibernate.
Eg.Core
model and mapping recipes from Chapter 1.ConfigByCode
.ConfigByCode
project, add references to NHibernate.dll
and NHibernate.ByteCode.Castle.dll
in the Lib
folder.ConfigByCode
, 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>
Program.cs
, add the following using
statements:using NHibernate.ByteCode.Castle; using NHibernate.Cfg; using NHibernate.Cfg.Loquacious; using NHibernate.Dialect;
Main
function, add the following code to configure NHibernate:var nhConfig = new Configuration() .Proxy(proxy => proxy.ProxyFactoryFactory<ProxyFactoryFactory>()) .DataBaseIntegration(db => { db.Dialect<MsSql2008Dialect>(); db.ConnectionStringName = "db"; db.BatchSize = 100; }) .AddAssembly("Eg.Core"); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate Configured!"); Console.ReadKey();
In this recipe, we create an identical NHibernate configuration using extension methods in the NHibernate.Cfg.Loquacious
namespace. These methods offer full type safety and improved discoverability over code configurations in the previous version of NHibernate.
We specify proxyfactory.factory_class
using the Proxy
extension method. Next, we specify dialect
, connection.connection_string_name
, and adonet.batch_size
with the DatabaseIntegration
extension method. Finally, we add the embedded resource mappings with the AddAssembly
method. AddAssembly
isn't an
extension method, and has been a part of the NHibernate configuration API for many versions.
Notice that we are still referencing the db
connection string defined in our App.config
file. If we wanted to eliminate the App.config
file entirely, we could hardcode the connection string with this code:
db.ConnectionString = @"Connection string here...";
This, however, is completely inflexible, and will require a full recompile and redeployment for even a minor configuration change.