Dynamic swappable Data Access Layer

Posted by Andy on Stack Overflow See other posts from Stack Overflow or by Andy
Published on 2010-05-07T12:16:23Z Indexed on 2010/05/07 13:08 UTC
Read the original article Hit count: 165

I'm writing a data driven WPF client. The client will typically pull data from a WCF service, which queries a SQL db, but I'd like the option to pull the data directly from SQL or other arbitrary data sources.

I've come up with this design and would like to hear your opinion on whether it is the best design.

First, we have some data object we'd like to extract from SQL.

// The Data Object with a single property
public class Customer
{
    private string m_Name = string.Empty;

    public string Name 
    {
        get { return m_Name; }
        set { m_Name = value;}
    }
}

Then I plan on using an interface which all data access layers should implement. Suppose one could also use an abstract class. Thoughts?

// The interface with a single method
interface ICustomerFacade
{
    List<Customer> GetAll();
}

One can create a SQL implementation.

// Sql Implementation
public class SqlCustomrFacade : ICustomerFacade
{
    public List<Customer> GetAll()
    {
        // Query SQL db and return something useful
        // ...

        return new List<Customer>();
    }
}

We can also create a WCF implementation. The problem with WCF is is that it doesn't use the same data object. It creates its own local version, so we would have to copy the details over somehow. I suppose one could use reflection to copy the values of similar fields across. Thoughts?

// Wcf Implementation
public class WcfCustomrFacade : ICustomerFacade
{
    public List<Customer> GetAll()
    {
        // Get date from the Wcf Service (not defined here)
        List<WcfService.Customer> wcfCustomers = wcfService.GetAllCustomers();

        // The list we're going to return
        List<Customer> customers = new List<Customer>();

        // This is horrible
        foreach(WcfService.Customer wcfCustomer in wcfCustomers)
        {
            Customer customer = new Customer();
            customer.Name = wcfCustomer.Name;
            customers.Add(customer);
        }

        return customers;
    }
}

I also plan on using a factory to decide which facade to use.

// Factory pattern
public class FacadeFactory()
{
    public static ICustomerFacade CreateCustomerFacade()
    {
        // Determine the facade to use
        if (ConfigurationManager.AppSettings["DAL"] == "Sql")
            return new SqlCustomrFacade();
        else
            return new WcfCustomrFacade();
    }
}

This is how the DAL would typically be used.

// Test application
public class MyApp
{
    public static void Main()
    {
        ICustomerFacade cf = FacadeFactory.CreateCustomerFacade();
        cf.GetAll();
    }
}

I appreciate your thoughts and time.

© Stack Overflow or respective owner

Related posts about object-oriented-design

Related posts about polymorphism