ObjectContextFactory Guidelines

This design pattern shows how to implement the factory pattern for the ObjectContext and storage creation process in your application. The sample shows how to implement the factory for the AccessStorage, but it's very easy to adopt it for other storages.

Our factory class is marked static and contains only one method with name GetObjectContext. This method returns a fully initialized ObjectContext instance.

Attention: This implementation of the factory is supposted to work in a single threaded windows application. To work in a multi threaded or ASP.NET application the persistent objects should implement the ISelfContainingObject interface and the factory should return for each call a new instance of the ObjectContext.

The class itself is very simple to write. The following sample shows how:

C#
// Returns fully initialized instances of the ObjectContext.
public static class ObjectContextFactory
{
    private static ObjectContext _context;

    // Returns a new fully initialized instance of the ObjectContext.
    public static ObjectContext GetObjectContext()
    {
        if (_context == null)
        {
            // Create a connection to the database.
            _context = new ObjectContext(new AccessStorage(@"C:\", "db.mdb"));
            // Set a concurrency manager.
            _context.ConcurrencyManager = new Md5ConcurrencyManager();
        }

        return _context;
    }
}

VB.NET
' Returns fully initialized instances of the ObjectContext.
Public Class ObjectContextFactory

    Private Shared _context As ObjectContext

    ' Returns a new fully initialized instance of the ObjectContext.
    Public Shared Function GetObjectContext() As ObjectContext
        If _context Is Nothing Then
            ' Create a connection to the database.
            _context = New ObjectContext(New AccessStorage("C:\", "db.mdb"))
            ' Set a concurrency manager.
            _context.ConcurrencyManager = New Md5ConcurrencyManager()
        End If

        Return _context
    End Function

End Class

To use the class in the application's code, the GetObjectContext method needs only to be called without creating an instance of the factory class.

C#
// Get an instance of the ObjectContext.
ObjectContext context = ObjectContextFactory.GetObjectContext();

VB.NET
' Get an instance of the ObjectContext.
Dim context = ObjectContextFactory.GetObjectContext()

If the connection string or the type of storage changes you need only to change that in your factory class.

Last edited Nov 24, 2009 at 5:12 PM by davidbrown, version 1

Comments

No comments yet.