tags:

views:

37

answers:

1

In my project I have about 10 DataContext. My question is whether I have to use global instance or create each single instance of datacontext in a method. Which of the method (from method1 and method2) is better from design point of view.

public class Database
{

    USDataContext USDB = new USCDataContext();

    //Method 1 Global instance
    public void update US_CountryTable()
    {
        USDB.updateCountryTable();
    }

    // Method 2 individual instance
      public void Update CountryTable(string country)
      {
         switch (country)
        {
            case:GB
                GBDataContext GBDB = new GBCDataContext();
                GBDB.updateCountryTable();

                // Some suggest this may be helpful
                // using (GBDataContext  dbContext = new GBDataContext ())
                // { GBDB.updateCountryTable();
                // }
             break;
             case: US
                USDataContext USDB = new USCDataContext();
                USDB.updateCountryTable();
             break;
        } 

      }
}

Thanks

A: 

I would actually use a combination of the two approaches. I would use a Singleton class to allow access to a central DataContext handler object, and a secondary class that held the individual data access methods. I would also implement using blocks to make sure my DataContext was initialized clean and disposed fresh with each request.

public sealed class AppDC
{
    static readonly ApplicationDataContext _Instance = new ApplicationDataContext();

    static AppDC()
    {
    }

    AppDC()
    {
    }

    public static ApplicationDataContext Instance
    {
        get { return _Instance; }
    }
}

public static class ApplicationDataContext
{
    public static void DataAccessOne()
    {
        using (DataContext dc = new DataContext())
        {
            ...
        }
    }

    public static void DataAccessTwo()
    {
        using (DataContext dc = new DataContext())
        {
            ...
        }
    }
}
Neil T.
GBDataContext and USCDataContext() they are diff databases ,so I have to create two separate AppDC Class??
NETQuestion
Not if you don't want to. For example, the DataAccessOne method could use the GBDataContext, and the DataAccessTwo method could us the USCDataContext. You can reference as many different DataContexts as you wish within the ApplicationDataContext class, but you only have to reference the single AppDC.Instance in your code. For example, to call the DataAccessOne method: AppDC.Instance.DataAccessOne().
Neil T.