Friday, June 27, 2008

Use a Web.Config connection string in your Data Access Layer with LINQ To SQL

My applications have the Business and Data Access Layers in a separate DLL from the presentation. This makes it so that everything that wants to do a certain function uses the same library. I also like to pre-compile my web sites which means that I can't get at the app.config if I need to make changes to the connection string (moving around dev, test, prod, etc). I found this from Jason Gaylord that worked quite well.

As I worked with it, I began to think that there might be a better way to handle it. My answer was a simple factory pattern class to create my datacontext. I'd like to claim the idea but I really got it from the Enterprise Application Block's DatabaseFactory.

Instead of adding an additional constructor I simply create a class that has the responsibility for creating the datacontext. The CreateDataContext method determines the correct connection string and then uses the predefined constructors. I place this class in the code file for the LINQ To SQL since I consider it part of the DAL.

Public Class AdventureWorksDataContextFactory    
    Public Shared Function CreateDataContext() As AdventureWorksDataContext        
        Dim connStr = ConfigurationManager.ConnectionStrings("AdventureWorksConnectionString").ConnectionString        
        Return New AdventureWorksDataContext(connStr)    
    End Function
End Class

When I want to create my datacontext I simply need to issue the following command.

Dim dc = AdventureWorksDataContextFactory.CreateDataContext

The nice part about this is that I can have my method do all sorts of stuff and it's neatly separated from the datacontext itself. I can overload the method if needed.

Enjoy.

Subscribe in a reader

No comments: