Have you ever wanted to code something that wasn’t exactly best practices, but would make for a neat concept?  I know that I have.  I seem to be constantly pushing against the edges of best practices hoping to find the next “Dependency Injection” concept that makes everyones lives just a little bit easier.  While my current spike project is not of that caliber, it is pushing the boundaries in a weird sort of way.  So instead of just laughing at myself, I thought that I’d open up access to it and let you guys laugh at me as well.  So what is this spike that I’m talking about?  This is a database driver for NHibernate that works accross the network, or across WCF specifically.

The concept is very simple.  NHibernate, at its very base relies on an IDbConnection to go out and fetch the data from the database.  Normally this connects rather directly to the db in a low latency connection.  Being an intensely curious programmer I wondered if it would be possible to route this raw db connection over top of a WCF connection.  The cool things is that it works, although introducing more latency than is optimal of course.  It works by opening up the actual db connection on the server and then reading the data associated with a command into a dataset which is transmitted accross WCF.  On the client side a datareader is created from the dataset thus allowing the client to read the database and perform other operations.

How reliable is this concept.  Well I haven’t had the chance to use it in any production apps.  (Not sure that I’d want to) but it does pass all of NHibernate 2.0.1GA’s test save one that deals with schemas. Let’s say that this piques your interest a little bit and you would like to try it out.  I’m not going to be releasing binaries and a big how to, but here’s the SVN url and you can give it a try for yourselves.

http://slagd.com/svn/NHibernate.WCFDriver/Trunk

There is a project in the source called “TestServer” which is simply a console project that will host the server.  The server is the only part that has a custom configuration element in the app.config.  Both the server and the client rely on standard WCF configuration to create a connection.  You can find examples of this configuration in both the app.config of the NHibernate.Test-2.0 project and the app.config of the TestServer project.  It’s also important to note that when you are using the WCFDbDriver on the client, the NHibernate connection string setting is ignored.  You can put whatever you want there but you will have to give it a value or NHibernate will complain.  Actual client-server connection information is located in the WCF configuration elements.

This is definitely not in keeping with best-practices but who says you can’t have fun with programming sometimes.

It’s been a while since I’ve done anything with the GenericMessaging project which is too bad since I consider it to be the most useful of the projects that I have been working on lately. Last week I ran into a painful brick wall regarding the security system I’ve been working on, so I decided to do some reworking on GenericMessaging while my brain sorts itself out and develops new neural pathways to replace the fried ones. There have been several comments on the forum about GenericMessaging, mostly regarding its dependence on PostSharp. While I think that PostSharp is great, it’s probably not something that needs to be intimately linked with the GenericMessaging layer. I’ve abstracted PostSharp support out into its own separate library. I’ve also added a new library that contains a class that will dynamically create a proxy for you using the Castle Dynamic Proxy Generator. This should give users more flexibility. I’ve uploaded these changes to the svn repositories but I won’t update the binaries quite yet as there is some more refactoring that needs to take place. So go grab the latest version from svn and give it a whirl.

Oh and a big thanks to those people who have posted on the forum with suggestions.

I have had the very bad fortune to be working with some very old database structures at the moment. Upgrading those structures is not possible, however there are times when it would be nice to map against them.  Recently I have been banging my head against a scenario where an entity may exist in one database at “X” location and in an entirely different database at “Y” location.  This works fine as long as this database is the only one that you are connecting and mapping too.  You can simply change the database name in the connection string and life is good.  However there are situations - mine in particular - where you have to map relations between your entities across databases, ouch.  In this situation a person needs to prefix the names of their table mappings with the database name as well.  This seems to work at least until you need to change the name of the database that you are connecting to.

So is this situation even possible with NHiberante(2.0.1GA)?  It turns out that yes it is, but first you have to get NHibernate to perform some gymnastics.  This seems to work fine for me but that is not a guarantee that your experience will be similar.  There is an additional caveat as well, that is that this only works for specifying the db names before you start an NH session factory.  Once you start the session the names are finalized and this method will not work to change them.   This method actually works by putting placholder values in your mapping files instead of actually database names.  What we need to do then is to strip out the placeholders and replace them with real db names when the NH session factory is being created.  We do this by looking through the configuration file that is generated by NH and replacing our values before the session factory is created.  In theory this would also work with table names as well as db names, but that is not something that I have tested with.

Lets start out with a very simple mapping.  Remember that we are not exactly sure of the database name that this will be residing in.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MemX.Data.Entities" namespace="MemX.Data.Entities.RMS">
  <class name="Item" table="$RmsDB.dbo.Item" lazy="false">
    <id name="ID" column="ID" type="Int32">
      <generator class="native" />
    </id>
    <property name="Description" column="Description"/>
  </class>
</hibernate-mapping>

What you can see, when you look at the attribute containing the table name, is that we’ve put a placeholder there instead of the actual table name.

Now that we have a placeholder there instead of a database name we need a class that can help us to easily modify NH’s configuration.  Lets start out with a dictionary to contain our placholder to value mappings.

/// <summary>
/// Helps to map table symbols in the NH mappings to actual table/database names
/// </summary>
public class NHTableMappings
{
    /// <summary>
    /// Maps from the placeholder string to the real table/database name
    /// </summary>
    public IDictionary<string, string> Mappings { get; protected set; }
 
    /// <summary>
    /// Creates a set of table/database mappings
    /// </summary>
    public NHTableMappings()
    {
        Mappings = new Dictionary<string, string>();
    }
}

And to push those mappings into the NH configuration we would need to do something like this inside our NHTableMappings class.

/// <summary>
/// maps table symbols to actual table/database names
/// </summary>
/// <param name="configuration"></param>
/// <returns></returns>
public void MapTables(Configuration configuration)
{
    if (configuration == null) throw new ArgumentNullException("configuration");
 
    //get the tables using reflection
    FieldInfo tablesField = typeof (Configuration).GetField("tables", BindingFlags.Instance | BindingFlags.NonPublic);
    IDictionary<string, Table> tables = tablesField.GetValue(configuration) as IDictionary<string, Table>;
 
    if(tables == null)
        throw new InvalidOperationException("Couldn't retrieve table information from NHibernate configuration.");
 
    //look through NHTableMappings
    foreach (KeyValuePair<string, string> key_tableName in Mappings)
    {
        string tableKey = key_tableName.Key;
        string tableName = key_tableName.Value;
 
        IEnumerable<Table> tablesToChange = tables.Where(p => p.Key.Contains(tableKey)).Select(p => p.Value);
        foreach (Table table in tablesToChange)
        {
            table.Name = table.Name.Replace(tableKey, tableName);
        }
    }
}

It’s pretty simple really.  We use reflection to get the tables field from the NH configuration because it is not public.  We scan through the table names looking for keys that are in our mapping and we do the old switcheroo.  Once this has been done we can start up a session factory and our entity will now be mapped against the correct database.

//Build the NH configuration
Configuration nhConfiguration = new Configuration().Configure();
 
//add your mappings
NHTableMappings tableMappings = new NHTableMappings();
tableMappings.Mappings.Add("$RmsDB", "MyRmsDatabaseName");
 
//modify the NH configuration
tableMappings.MapTables(nhConfiguration);
 
//build your session factory
ISessionFactory sessionFactory = nhConfiguration.BuildSessionFactory();

I hope this helps someone who is trying solve the same problem that I was.

I’ve included some complete classes here in case you just want to copy and paste (plus some includes).

The main class.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using NHibernate.Mapping;
using Configuration=NHibernate.Cfg.Configuration;
 
namespace MemX.Data
{
    /// <summary>
    /// Helps to map table symbols in the NH mappings to actual table/database names
    /// </summary>
    public class NHTableMappings
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NHTableMappings));
        public static readonly string ConfigSection = "nh-table-mappings";
        public static readonly string ConfigKey = "mapping";
        public static readonly string KeyAttribute = "table-key";
        public static readonly string NameAttribute = "table-name";
 
        /// <summary>
        /// Maps from the placeholder string to the real table/database name
        /// </summary>
        public IDictionary<string, string> Mappings { get; protected set; }
 
        /// <summary>
        /// Creates a set of table/database mappings
        /// </summary>
        public NHTableMappings()
        {
            Mappings = new Dictionary<string, string>();
        }
 
        /// <summary>
        /// Adds a mapping from a key to an actual name
        /// <para>Can be used for table names or DB names</para>
        /// </summary>
        /// <param name="tableKey"></param>
        /// <param name="tableName"></param>
        /// <param name="overwrite">Do we want to overwrite an existing value</param>
        public void AddMapping(string tableKey, string tableName, bool overwrite)
        {
            if (String.IsNullOrEmpty(tableKey)) throw new ArgumentNullException("tableKey");
            if (String.IsNullOrEmpty(tableName)) throw new ArgumentNullException("tableName");
 
            if (!Mappings.ContainsKey(tableKey))
                Mappings.Add(tableKey, tableName);
            else if(overwrite)
                Mappings[tableKey] = tableName;
        }
 
        /// <summary>
        /// maps table symbols to actual table/database names
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public void MapTables(Configuration configuration)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
 
            //get the tables using reflection
            FieldInfo tablesField = typeof (Configuration).GetField("tables", BindingFlags.Instance | BindingFlags.NonPublic);
            IDictionary<string, Table> tables = tablesField.GetValue(configuration) as IDictionary<string, Table>;
 
            if(tables == null)
                throw new InvalidOperationException("Couldn't retrieve table information from NHibernate configuration.");
 
            //look through NHTableMappings
            foreach (KeyValuePair<string, string> key_tableName in Mappings)
            {
                string tableKey = key_tableName.Key;
                string tableName = key_tableName.Value;
 
                IEnumerable<Table> tablesToChange = tables.Where(p => p.Key.Contains(tableKey)).Select(p => p.Value);
                foreach (Table table in tablesToChange)
                {
                    table.Name = table.Name.Replace(tableKey, tableName);
                }
            }
        }
 
        /// <summary>
        /// Reads the configuration from xml
        /// </summary>
        /// <param name="section"></param>
        /// <param name="overwrite">Do we want to overwrite existing configuration</param>
        public void ReadFromXml(XmlNode section, bool overwrite)
        {
            log.Debug("Reading table mappings from xml");
            if (section == null) throw new ArgumentNullException("section");
 
            if(section.LocalName != ConfigSection)
                throw new ConfigurationErrorsException(String.Format("Invalid section {0} in NHTableMappings configuration", section.LocalName));
 
            foreach (XmlNode node in section.ChildNodes)
            {
                if(node.LocalName != ConfigKey)
                    throw new ConfigurationErrorsException(String.Format("Invalid section {0} in NHTableMappings configuration", node.LocalName));
 
                string tableKey = node.Attributes[KeyAttribute].Value;
                string tableName = node.Attributes[NameAttribute].Value;
 
                AddMapping(tableKey, tableName, overwrite);
            }
        }
 
        /// <summary>
        /// Creates the mappings from an xml section
        /// </summary>
        /// <param name="section"></param>
        /// <param name="overwrite">Do we want to overwrite existing configuration</param>
        /// <returns></returns>
        public static NHTableMappings CreateFromXml(XmlNode section, bool overwrite)
        {
            NHTableMappings tableMappings = new NHTableMappings();
            tableMappings.ReadFromXml(section, overwrite);
 
            return tableMappings;
        }
 
        /// <summary>
        /// Creates the mappings from a config section
        /// </summary>
        /// <returns></returns>
        public static NHTableMappings CreateFromConfig()
        {
            NHTableMappings tableMappings = ConfigurationManager.GetSection(ConfigSection) as NHTableMappings;
            if(tableMappings == null)
                throw new ConfigurationErrorsException("Could not load table mappings confugration from app/web.config");
 
            return tableMappings;
        }
 
        /// <summary>
        /// Creates the mappings from a config section if it exists, or defaults to an empty mappings file
        /// </summary>
        /// <returns></returns>
        public static NHTableMappings CreateFromConfigOrDefault()
        {
            NHTableMappings mappings;
 
            try
            {
                mappings = CreateFromConfig();
            }
            catch (ConfigurationErrorsException)
            {
                mappings = new NHTableMappings();
            }
 
            return mappings;
        }
    }
}

A configuration section handler.

using System.Configuration;
using System.Xml;
 
namespace MemX.Data
{
    public class NHTableMappingsConfigurationSectionHandler : IConfigurationSectionHandler
    {
        #region IConfigurationSectionHandler Members
 
        public object Create(object parent, object configContext, XmlNode section)
        {
            return NHTableMappings.CreateFromXml(section, true);
        }
 
        #endregion
    }
}

The usage looks something like this.

<configuration>
  <configSections>
    <section name="nh-table-mappings" type="MemX.Data.NHTableMappingsConfigurationSectionHandler, MemX.Data"/>
  </configSections>
  <nh-table-mappings>
    <mapping table-key="$RmsDB" table-name="RMSCal3"/>
  </nh-table-mappings>
</configruation>

And even an extension method

    public static class NHTableMappingsExtension
    {
        public static Configuration MapTables(this Configuration configuration)
        {
            NHTableMappings tableMappings = NHTableMappings.CreateFromConfig();
 
            tableMappings.MapTables(configuration);
 
            return configuration;
        }
    }

Using the configuration and the extension it would looking something like this.

            ISessionFactory sessionFactory = new Configuration()
                .Configure()
                .MapTables()
                .BuildSessionFactory();

You could also include some default mappings and include them as a resource along with your mappings and only override when needed as well.

A few months ago I made the switch from CastleWindsor to StructureMap for my dependency injection needs. It’s a more active project, more up to date with the times, more extensible, and definitely has a better interface for configuring through code rather than xml. After a few growing pains I’ve grown to like it a lot ( I’m using version 2.5). However in the last few days I’ve run into a roadblock it seems, and it all has to do with the lifecycle/scope of objects.

A lot of dependency objects in the typical application could be singletons if designed right (covers head from flames). However there is a point at which that ceases to be the case, that’s where unit of work patterns come into play. A unit of work has only a finite lifespan and should then be disposed. In keeping with good testability and design patterns you will probably also want to have a ready made unit of work object injected into the classes that need them. Every time that you ask for a unit of work you should be supplied with a fresh new copy. That’s where configuring the lifecycles properly in your DI tool should come into play.

As code is a common language, I will code out what I am talking about as simply as possible.

//Think of this as a data session
public class Session
{
}
 
public class Model1
{
    public Session Session { get; set; }
 
    public Model1(Session session)
    {
        Session = session;
    }
}
 
public class Model2
{
    public Session Session { get; set; }
 
    public Model2(Session session)
    {
        Session = session;
    }
}
 
//this is my shell, it needs some models
public class Shell
{
    public Model1 Model1 { get; set; }
    public Model2 Model2 { get; set; }
 
    public Shell(Model1 model1, Model2 model2)
    {
        Model1 = model1;
        Model2 = model2;
    }
}

This is a pretty straight forward scenario. We have a shell (entry point) that contains a couple of models, each of these models requires a unique data session so that it can pull and work with its data independently.

Let’s use StructureMap to wire these together so that we just create our shell and have its dependencies filled for us automatically. Remember that by default StructureMap does not create singletons, so using the default config should result in transient, per-request objects.

ObjectFactory.Initialize(
    x =&gt; {
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
    });

Now let’s test to make sure that we have a unique data session.

Shell shell = ObjectFactory.GetInstance();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

And this is where we come to the fail part. The data session contained in each model is identical, the same as if we had declared it as a singleton. We know that the configuration is right because doing it this way works.

Assert.AreNotEqual(ObjectFactory.GetInstance(), ObjectFactory.GetInstance());

Why this happens has been a matter of great curiosity to me, and even though I’m not a great StructureMap expert I’ll hazard an educated guess. Each time that you make a declarative request for the root of an object graph, StructureMap creates a unique BuildSession. Inside that build session there is a cache of instantiated objects. The session then builds one object for each dependency in the graph no matter how many times it is requested in that graph. The objects may be built or pulled using a variety of methods but once they are built and stored in the graph then they are not requested to be built again for the lifetime of that BuildSession. This means that for a given declarative request you will only ever have one object per type instantiated. If, like me, you are starting your application from a bootstrapper this effectively turns all of your objects into singletons.

Lets try the same scenraio in CastleWindsor.

WindsorContainer container = new WindsorContainer();
 
container.AddComponentWithLifestyle("Session", typeof(Session), LifestyleType.Transient);
container.AddComponentWithLifestyle("Model1", typeof(Model1), LifestyleType.Transient);
container.AddComponentWithLifestyle("Model2", typeof(Model2), LifestyleType.Transient);
container.AddComponentWithLifestyle("Shell", typeof(Shell), LifestyleType.Transient);
 
Shell shell = container.Resolve();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

This works, both data sessions are unique. Let’s try AutoFac.

var builder = new ContainerBuilder();
 
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
 
var container = builder.Build();
 
Shell shell = container.Resolve();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

Again this works as well.

How can this problem be solved by mere mortals? Well the most obvious solution would be to pass factories that can create your transient objects instead of just passing the transient objects themselves. However this is not ideal as it just leads to more code noise that should be handled by the DI component.

Can we use an interceptor? Unfortunately this approach does not work as your custom interceptor will be called only once per BuildSession resulting in the same problem. The same is true for using a ConstructorInstance. As this post ends I have been searching for a way of getting true instanced objects out of structuremap for most of a day with no success. In ending let me say that I am open to any expertise you may offer on this subject, and if I do find the answer I will most definitely post an update to this article.

Update
It would appear that there is no good way to do this using StructureMap. There is a workaround that though arduous could work for more limited scenarios. The trick is to define the dependency for the object that needs a transient type.

x.BuildInstancesOf()
    .TheDefault.Is.OfConcreteType().CtorDependency().Is( x.OfConcreteType() );

Though this works it wouldn’t be really practical if your dependency is used in numerous places. The reasons that the author chose to limit transients to only once per session are valid and advantageous for his situation but causes some problems elsewhere. What I would have preferred was that the BuildSession caching was done with an interceptor the same way as singleton caching. That way not every instance would be limited by the BuildSession caching and other implementations could be provided.

Update

As Bart Deleye pointed out in the comments the latest version of StructureMap now properly supports this scenario with the following syntax.

.ForRequestedType().TheDefaultIsConcreteType().AlwaysUnique()

Thus resulting in a very happy ending due to the flexibility and collaborative nature of open source software.  Thanks Jeremy

kick it on DotNetKicks.com

Creating clean testable code is one of the major challenges when creating complicated, composite user interfaces.  To help with this a variety of patterns have cropped up including MVC, MVP, and most notably for WPF the MVVM pattern.   These patterns work fine for the most part at least until your view gets a little bit too complicated.  What is a programmer supposed to do with the added complexity?  You should be separating common logic out into self contained controls, each with their own view models.  This is easier said then done, as you need to make sure that you provide view models for each of the controls your view implements.  While this is probably the more accepted way of doing things, it leads to a lot of code noise and increased complexity when writing tests for your main view model.

There is another way and you can get there by using the Markup Extensions that are available to exend WPF.  Because I’m a bit to lazy to create my own custom binding extension, I used one that I found here http://www.hardcodet.net/2008/04/wpf-custom-binding-class .  This fellow has already explored custom bindings and has created an easy to use base class for creating and manipulating custom WPF bindings.

With this class in place it is a fairly trivial operation to create a databinding class that utilizes your favorite dependency injector.  For this sample I am using StructureMap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    /// <summary>
    /// Binds to a dependency injected object
    /// </summary>
    public class DIBinding : BindingDecoratorBase
    {
        /// <summary>
        /// The type we are looking for
        /// </summary>
        public Type Type { get; set; }
 
        /// <summary>
        /// The key if applicable
        /// </summary>
        public string Key { get; set; }
 
        public override object ProvideValue(IServiceProvider provider)
        {
            //use DI to get the value
            if(Type == null)
                throw new InvalidOperationException("You must specify a type for this binding");
 
            Source = String.IsNullOrEmpty(Key) ? ObjectFactory.GetInstance(Type) : ObjectFactory.GetNamedInstance(Type, Key);
 
            return base.ProvideValue(provider);
        }
    }

Once we have created this binding helper we can use it in any xaml file provided that we include the proper namespaces of course.

1
<TreeView ItemsSource="{DataBinding:DIBinding Type=MainNav:IMainNavigationMenu, Path=MenuItems}" />

Use of dependency injection in your xaml files should be limited to where it is appropriate.  Of course it is not appropriate to do you whole application in this manner, but for certain controls it can lead to a much cleaner more testable view model for rest of your code.