开发者

effective way of using Multiple DataContext

开发者 https://www.devze.com 2022-12-15 08:28 出处:网络
In my project I have about 10 DataContext. My question is whether I have to use global instance orcreate each single instance of datacontextin a method.Which of the method (from method1 and method2) i

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


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())
        {
            ...
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号