Creating database connections with Unity – part 2


Last time we looked at how to set up the configuration file so that Unity would wire up an object that took an IDbConnection parameter in its constructor. Whilst the solution works, it is easy for the various connection strings to become buried away in the Unity configuration. Also, the application configuration file already has somewhere to put connection details: the connectionStrings Element. This seemed like the ideal place to store my connection strings so I wanted a way to hook this up using Unity. After hunting around the documentation for a while, I noticed that as well as specifying parameters as dependencies (as in the previous post) you can also specify a value. This value has to be entered as a string in the configuration file but you can use the typeConverter attribute to specify the type converter that should be used to turn the string into the appropriate type. At this point the light bulb flicked on and DbConnectionNameTypeConverter entered stage left.

NOTE: the code below isn’t production ready (and as always, is subject to the standard disclaimer: “These postings are provided "AS IS" with no warranties, and confer no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm”).

public class DbConnectionNameTypeConverter : TypeConverter
{
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        string connectionStringName = (string) value;
        ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];

        DbProviderFactory providerFactory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
        IDbConnection connection = providerFactory.CreateConnection();
        connection.ConnectionString = connectionStringSettings.ConnectionString;
        return connection;
    }
}

This code simply takes the string passed in and looks up the connection details with that name. It uses the DbProviderFactory to create the connection, so it will handle SqlConnection or any other connection type that is registered. With this class in place, we can move the connection configuration to the connectionStrings section:

<connectionStrings>
    <add name="AdventureWorks"
         connectionString="Data Source=(local);Database=AdventureWorks;Integrated Security=SSPI;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

And then configure Unity to use the type converter to get an IDbConnection instance from the connection name:

<types>
    <type type="MyProject.IRepository, MyProject, Version=1.0.0.0, Culture=neutral"
          mapTo="MyProject.DefaultRepository, MyProject, Version=1.0.0.0, Culture=neutral">
        <lifetime type="transient" />
        <typeConfig>
            <constructor>
                <param name="connection" parameterType="IDbConnection">
                    <value value="AdventureWorks" type="IDbConnection" typeConverter="DbConnectionNameTypeConverter" />
                </param>
            </constructor>
        </typeConfig>
    </type>
</types>

And bingo! We get all of the Unity goodness from the previous post but reuse the existing configuration section to centralise the connection settings!

Comments (3)

  1. I was adding dependency injection to an existing project and opted to use Unity configured via the application

  2. Last time we looked at how to set up the configuration file so that Unity would wire up an object that

Skip to main content