Castle NHibernate Facility – Configuration

7. April 2009

Castle’s extensibility points provide you many ways to make your life easier. One and most widely used extensibility point is the facilities. By using facilities, you can integrate various other frameworks and technologies easily.

I am going to talk about NHibernate Integration Facility, which is currently lead by me. It was originally written by Hamilton Verissimo, and its current shape is more or less the same as what he wrote.

The purpose of this post is to get feedback and shape the documentation accordingly.

Now, after an historical introduction, lets talk about the facility’s purpose, and in as the first part of the documentation, the configuration.

The purpose
The purpose of this facility to provide an easy way to integrate NHibernate into MicroKernel backed applications. The facility provides a nice way to manage multiple session factories, a good way to manage sessions and it also provides some other structures that can be used to further integrate other frameworks such as Fluent NHibernate. It also plays nicely with other Castle services such as Transaction Management.


The Configuration
Currently, the facility can only be configured via XML, but it provides some extension points that can be used to configure it programmatically. The traditional way of configuring it is as given below. 

<configuration>
    <facilities>
        <facility
          id="nhibernatefacility"
          type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration"
          [optional: configurationBuilder="Your custom configuration builder"] [optional: isWeb="Your custom configuration builder"]>
            <factory id="sessionFactory1">
                <settings>
                    <item key="connection.provider">NHibernate.Connection.DriverConnectionProvider</item>
                    <item key="connection.driver_class">NHibernate.Driver.SqlClientDriver</item>
                    <item key="connection.connection_string">Data Source=.;Initial Catalog=test;Integrated Security=SSPI</item>
                    <item key="dialect">NHibernate.Dialect.MsSql2000Dialect</item>
                    <item key="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</item>
                </settings>
                <assemblies>
                    <assembly>YourAssembly.Name.Here</assembly>
                </assemblies>
            </factory>
        </facility>
    </facilities>
</configuration>
<httpModules>
    <add name="NHibernateSessionWebModule"
             type="Castle.Facilities.NHibernateIntegration.Components.SessionWebModule, Castle.Facilities.NHibernateIntegration"/>
</httpModules>

isWeb: In case of web application, you should set this to true, implement IContainerAccessor in your HttpApplication (the global.asax) also add following lines to your <httpModules> section


As it can bee seen here, it is not very much different from the way we configure NHibernate. What happens behind the scenes are that: Facility creates an NHibernate Configuration, registers the SessionManager, and make those ready to be resolved.

The facility provides you some way to modify the Configuration that is created behind the scenes. The point is called IConfigurationContributor. By implementing classes that derive from that interface and registering them to container, you’ll be able to modify the NHibernate Configuration, just before the SessionFactory is resolved. The interface is simple

public interface IConfigurationContributor
{
    void Process(string name,Configuration config);
}

 

The name corresponds to the id in the configuration.

You can also Configure NHibernate Configuration via the IConfigurationBuilder interface. Currently, there are 2 built in ConfigurationBuilders, namely DefaultConfigurationBuilder and XmlConfigurationBuilder.
The default one is the one that parses the thing you see above while XmlConfigurationBuilder uses NH’s native xmls.

In the next post, I will hopefully show to integrate FluentNHibernate using custom ConfigurationBuilder

, ,

An improvement on SessionFactory Initialization

14. March 2009

UPDATE: I have just committed the PersistentConfigurationBuilder for Castle NHibernate Facility. Thank you Jonathon Rossi for informing me!

We have received several complaints about slowness of SessionFactory initialization when there’s hundreds of entities, and Ayende has replied one of them here. It even gets worse if you’re using it in a web environment. You may think that it is not a problem since SessionFactory is initialized once in a web environment, but the major impact is not on production but development. Think how many times you start your application a day.

The problem is not really with NHibernate but with xml validation against the schema. Here are some profiler results for SessionFactory initialization with one thousand entities:

image

As you see, the adding XML resources takes the most time and the reason behind this is the schema validation. There is also an I/O cost involved (1040 resources should be read by NHibernate). There are several ways to get rid of it, one being the serialization of configuration. I spend 3 days (statics prevented me from spotting some bugs in the code) on this and I believe it pretty much works for every configuration. Another way of doing this is the merging of HBM files, which I believe faster than Serialization as Deserialization also takes some amount.

Now the results for the one using the Deserialized Configuration.

image

A nice feature of dotTrace allows us to compare the performance improvements over the old way.

image

We got 10 seconds rescued! Yay!

Now I am going to show how I used this feature in Castle NHibernate Facility. We have IConfigurationBuilder that is used to integrate various Configuration sources (such as FluentNHibernate).

First of all I must ensure that if any of the files that are used to create the Configuration change, we shouldn’t use the serialized configuration, instead the Configuration should be re-created.

public override Configuration GetConfiguration(IConfiguration config)
{
    log.Debug("Building the Configuration");

    string fileName = config.Attributes["fileName"];

    IConfiguration dependsOn = config.Children["dependsOn"];
    IList<string> list = new List<string>();

    foreach (var on in dependsOn.Children)
        list.Add(on.Value);

    Configuration cfg;
    if (IsNewConfigurationRequired(fileName, list))
    {
        log.Debug("Configuration is either old or some of the dependencies have changed");
        using(var fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
        {
            cfg = base.GetConfiguration(config);
            this.WriteConfigurationToStream(fileStream, cfg);
        }
    }
    else
    {
        using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
        {
            cfg = this.GetConfigurationFromStream(fileStream);
        }
    }
    return cfg;
}protected virtual bool IsNewConfigurationRequired(string fileName,IList<string> dependencies)
{
    if (!File.Exists(fileName))
        return true;
    FileInfo fi = new FileInfo(fileName);
    DateTime lastModified = fi.LastWriteTime;
    bool requiresNew=false;
    for (int i = 0; i < dependencies.Count && !requiresNew; i++)
    {
        FileInfo dependency = new FileInfo(dependencies[i]);
        DateTime dependencyLastModified = dependency.LastWriteTime;
        requiresNew |= dependencyLastModified > lastModified;
    }
    return requiresNew;
}

Code doesn’t look really good, I guess, so I am open to any suggestions on improvement. The code is not yet in Castle Codebase, as our NH dependency on trunk is not the latest (and i am too lazy to update it). When I find time, I may update the dependency if others agree.

There is one thing that you have to be careful about. You must be aware that if you’re using IUserType, IInterceptor, ISqlFunction etc, all of those should be Serializable too!

, ,

NHibernate Integration Facility - IConfigurationContributor

14. February 2009

Note: This short post is a self reminder about a feature that has just been added, I’ll probably use it in the documentation.

Our friend German Schuager has offered another cool feature, namely IConfigurationContributor. This interface allows implementors to change the Configuration instance _just before_ the ISessionFactory is created.

/// <summary>
/// Allows implementors to modify <see cref="Configuration"/>
/// </summary>
public interface IConfigurationContributor
{
    /// <summary>
    /// Modifies available <see cref="Configuration"/> instances.
    /// </summary>
    /// <param name="name">Name of the session factory</param>
    /// <param name="config">The config for sessionFactory</param>
    void Process(string name,Configuration config);
}


Implementors can modify the Configuration depending on the name.

, ,