2008-08-11

How to configure NHibernateFacility in code

I haven't started using Burrow yet, so I still depend on the NHibernateFacility in the castle stack. But I really don't like to pay my angle bracket tax, so I want to configure it in code.

   1: private void CreateItem(MutableConfiguration parent, string key, string value)
   2: {
   3:   MutableConfiguration item = parent.CreateChild("item");
   4:   item.Attributes.Add("key", key);
   5:   item.Value = value;
   6: }
   7:  
   8: public void Init()
   9: {
  10:   MutableConfiguration facility = new MutableConfiguration("facility");
  11:   facility.Attributes.Add("id", "nhibernatefacility");
  12:   facility.Attributes.Add("isWeb", "isWeb");
  13:   facility.Attributes.Add("defaultFlushMode", "Commit");
  14:   facility.Attributes.Add("type", "Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration");
  15:   MutableConfiguration factory = facility.CreateChild("factory");
  16:   factory.Attributes.Add("id", "nhibernate.factory");
  17:   MutableConfiguration settings = factory.CreateChild("settings");
  18:  
  19:   CreateItem(settings, "connection.provider", "NHibernate.Connection.DriverConnectionProvider");
  20:   CreateItem(settings, "connection.driver_class", "NHibernate.Driver.SqlClientDriver");
  21:   CreateItem(settings, "connection.connection_string", "Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=SSPI");
  22:   CreateItem(settings, "dialect", "NHibernate.Dialect.MsSql2005Dialect");
  23:   CreateItem(settings, "show_sql", "true");
  24:  
  25:   MutableConfiguration assemblies = factory.CreateChild("assemblies");
  26:   MutableConfiguration assembly = assemblies.CreateChild("assembly");
  27:   assembly.Value = "HomeForretningCore";
  28:  
  29:   IWindsorContainer container = new WindsorContainer(); 
  30:   container.Kernel.ConfigurationStore.AddFacilityConfiguration("nHibernateFacility", facility);
  31:   container.AddFacility("nHibernateFacility");
  32: }

2 comments:

Ken Egozi said...

cool stuff.
I also like to keep xml to minimum, however the connectionstring do belong in the config file imo, so I'd do
CreateItem(settings, "connection.connection_string_name", "MyDB");

instead of
CreateItem(settings, "connection.connection_string", "Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=SSPI");

Morten Lyhr said...

I think it depends on the type of application.

If the application only deploys to 3 locations (development, staging, and live). I dont see why I should not embed the 3 connections strings in the assemly, and choose one based on some artifact (machinename and/or others).