MicroLite 6.0 – Dynamic Connection Strings

Prior to MicroLite 6.0, in order to create a session factory you had to specify the connection name as defined in the connection strings section of your application configuration. This is generally a good idea as the connection string is a configuration value which should not be baked into the code as you would need a different value if you have separate Dev/Test/Production environments.

We did have a request from a MicroLite user to be able to specify the connection string at runtime as there is a requirement for that in his application so we have added functionality for doing just that.

The ForConnection methods now have an additional overload:

ForMsSql2005Connection(string connectionName, string connectionString, string providerName)

The reason that the new overload needs a connection name is to still allow support for the MVC and WebApi extensions which are dependent on a named connection to resolve the correct session factory.

The provider name needs to be the same as you would set in the connection string in the application config, this is used by MicroLite to resolve the correct DbProviderFactory.

This gives you two ways to configure a connection in MicroLite 6.0:

Option 1 (the recommended approach for most use cases)

Define the connection string in the application configuration

<connectionStrings>
    <add name="NorthwindDB"
         connectionString="Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=False;Integrated Security=SSPI;"
         providerName="System.Data.SqlClient" />
</connectionStrings>
// Create the session factory for the named connection
var sessionFactory = Configure
        .Fluently()
        .ForMsSql2005Connection("NorthwindDB")
        .CreateSessionFactory();

Option 2 (if you really really need to)

// Create the session factory with the specified name, connection string and provider name
var sessionFactory = Configure
        .Fluently()
        .ForMsSql2005Connection(
               "NorthwindDB",
               "Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=False;Integrated Security=SSPI;",
               "System.Data.SqlClient")
        .CreateSessionFactory();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s