Proper use of “Using” statement for datacontext

后端 未结 5 520
醉酒成梦
醉酒成梦 2021-02-06 05:08

I’m using Linq to Entities and lately, I found that a lot of folks recommending wrapping the datacontext in a using statement like this:

Using(DataContext db = n         


        
5条回答
  •  温柔的废话
    2021-02-06 06:10

    You can implement a Database factory which will cause your DbContext is being reused.

    You can achieve this as follows:

    DatabaseFactory class:

    public class DatabaseFactory : Disposable, IDatabaseFactory
    {
        private YourEntities _dataContext;
        public YourEntities Get()
        {
            return _dataContext ?? (_dataContext = new YourEntities());
        }
        protected override void DisposeCore()
        {
            if (_dataContext != null)
                _dataContext.Dispose();
        }
    }
    

    Excerpt of the Repository base class:

     public abstract class Repository : IRepository where T : class
    {
        private YourEntities _dataContext;
        private readonly IDbSet _dbset;
        protected Repository(IDatabaseFactory databaseFactory)
        {
            DatabaseFactory = databaseFactory;
            _dbset = DataContext.Set();
        }
    
        protected IDatabaseFactory DatabaseFactory
        {
            get;
            private set;
        }
    
        protected YourEntities DataContext
        {
            get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
        }
    

    Your table's repository class:

    public class ApplicationRepository : Repository, IYourTableRepository
    {
        private YourEntities _dataContext;
    
        protected new IDatabaseFactory DatabaseFactory
        {
            get;
            private set;
        }
    
        public YourTableRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {
            DatabaseFactory = databaseFactory;
        }
    
        protected new YourEntities DataContext
        {
            get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
        }
    
       }
        public interface IYourTableRepository : IRepository
       {
       }
    }
    

    This works perfectly together with AutoFac constructor injection as well.

提交回复
热议问题