Search code examples
c#.netdomain-driven-designdata-access-layer

Removing Data Access layer coupling from user interface


Currently my application's UI layer is coupled to my DAL dll. Dal is initialized like this:

//Initialize Data Access for AS400
Dal = JDE8Dal.Instance;
Dal.conString = Properties.Settings.Default.conAS400;

DAL is desinged as singleton. I thought that forcing the application to have one instance is a good idea.

DAL:

public class JDE8Dal
    {
        public string conString { get; set; }
        private static readonly JDE8Dal _instance = new JDE8Dal();
        private JDE8Dal()
        {
        }
        public static JDE8Dal Instance
        {
            get { return _instance; }
        }
        // Methods
    }

My BLL will look something like this:

namespace YLA.Barcode
{
    public static class YlaBarcodeUtil
    {
        public static string LotStripZeroes(string str)
        {
            var ret = str;
            if (str.Trim().StartsWith("00"))
            {
                ret = YlaGeneralUtilities.StripLeadingNumofChars(str, 2);
            }
            return ret;
        }
    }

public class BarcodeBLL
{
    //DAL INIT HERE?
}
}

Now that i need to build more applications i need to move into a 3 layer architecture and start reading on DDD.

1) How to move the DAL handling in BLL? Just add the initialization in my BLL section?

2) Should i keep my DAL design as singleton or not?


Solution

  • You should use the Inversion of Control pattern to reduce the dependency between your layers. In your case I would use a constructor injection as the data context is required by your class:

    public class BarcodeBLL
    {
        private JDE8Dal _context;
    
        public BarcodeBLL(JDE8Dal context)
        {
            _context = context;
        }
    }
    

    Data context should be short lived objects. If you're developing a web application you should instantiate one data context per request. I would also recommend using an ORM (Entity Framework / NHibernate).