Creating a sample WinForms application, part two: the data access layer

In part one of this series I provided you with an overview of what I hope to accomplish. We’ll be starting our sample application with an Xpo back-end that will reside as its own project without our overall solution. The nice thing about Xpo is that your classes, data access and UI don’t all need to reside within the same project or namespace. Because of this flexibility, I like to segregate my data access layer (or DAL for short) to its own project so that it could be changed easily to take advantage of the the different ways Xpo can connect to your data store (or even what data store Xpo connects to).

Xpo has a default data layer, known as XpoDefault.Session. If you choose to use this, all newly created Xpo objects will automatically use and share this default data layer. Of course, this method isn’t recommended by DevExpress and won’t really work well in multi-threaded or ASP.NET applications.

Instead of relying on XpoDefault.Session, we’ll create an XpoDefault.DataLayer instance and actually set the XpoDefault.Session to null to ensure that it’s never used. It’s safe to use the XpoDefault.DataLayer static instance, but you could choose to provide a reference to your data layer when instantiating a Session or UnitOfWork object if you wanted.

We have two options to choose from when it comes to creating this XpoDefault.DataLayer:

  • SimpleDataLayer – Used by default.Use this DAL if you need to modify the object metadata at runtime.
  • ThreadSafeDataLayerUse this DAL if multiple threads are allowed to access data in a data store.

Source: IDataLayer documentation

We’ll choose to use the ThreadSafeDataLayer in the event that we want to use threading in our application.

Beyond that, we need to provide a Data Store–namely our database server. We can provide a connection string to the ThreadSafeDataLayer constructor so that it knows where it’s getting and saving our data to/from:

/// <summary>
/// Sets the application's default data layer
/// </summary>
internal override void SetDataLayer()
    string ConnectionString = "Data Source=MySqlServer\\sqlexpress;integrated security=SSPI;initial catalog=DxContactList";

    XPDictionary dictionary = MetaDataDictionary.GetMetaDataDictionary();
    XpoDefault.DataLayer = new ThreadSafeDataLayer(dictionary, XpoDefault.GetConnectionProvider(ConnectionString, AutoCreateOption.DatabaseAndSchema));
    XpoDefault.Session = null;

}   //End the SetDataLayer() method

We’ll invoke that method from the Program class when the application starts up, and we’re essentially done at this point. Any new Session or UnitOfWork component used within our application will automatically connect via this data layer.

In part three of this series, we’ll begin building our Xpo business class objects.

Creating a sample WinForms application, part two: the data access layer